【问题标题】:How to convert nsstring into nsdate in iphone如何在 iphone 中将 nsstring 转换为 nsdate
【发布时间】:2011-09-06 04:30:05
【问题描述】:

我想将 nsstring 转换为 nsdate 。我创建了一个全局变量,我保存从 datepicker 中选择的日期,然后将此变量转换为 nsdate 我们使用 datefromstring 函数。但是字符串没有转换为 date。什么可能是问题所在。

TTimePickercontroller:
This is the class in which i have the code for the picker

-(NSString *)convertDueDateFormat{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setFormatterBehavior: NSDateFormatterBehavior10_4];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    dateString = [dateFormatter stringFromDate:datePicker.date];

    return dateString;
//dateString is an nsstring variable that has been declared globally.
}

TAddAlarmController.
this is another class in which i want to convert the dateString varibale into nssdate
-(IBAction)save{

    timepicker = [[TTimePickerController alloc]init];
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"hh:mm"];
    d = [df dateFromString:dateString];
    NSLog(@"%@", d);
    //Here i am using the dateFromString function and converting the string variable dateString into nsdate variable d .in dateString variable value is getting passed but in d the value is not getting passed. 


}
Please help me in solving the problem.Thanks

【问题讨论】:

标签: iphone objective-c


【解决方案1】:
-(NSString *)convertDueDateFormat{

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm"];
 dateString = [dateFormatter stringFromDate:datePicker.date];
   ////some code    

}

Try like this,

【讨论】:

  • 但是当我在控制台中将其转换为 d 时,它显示:1970-01-01 05:24:00 +0000
【解决方案2】:
Try this code this will help you because I run this code successfully and return time.

UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];  
pickerView.datePickerMode = UIDatePickerModeDate;  
pickerView.hidden = NO;  
pickerView.date = [NSDate date];
[self.view addSubview:pickerView];
NSString *dateString;   
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm"];
dateString = [dateFormatter stringFromDate:pickerView.date];
NSLog(@"String into Date:--->%@",dateString);

【讨论】:

  • nikunj 但是当我将此 dateStrimg 转换为 nsdate 时,它​​没有得到正确转换。
  • 如果我选择 1.00 pm 它会在我的 nsdate 变量中显示 7.30 pm
  • 等待 10 分钟,我实现你的演示
  • 试试这个链接这对你有帮助stackoverflow.com/questions/3917250/…
  • 为什么需要 nsdate 以及在哪里显示?请告诉我,让我解决你的问题
猜你喜欢
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
  • 2015-08-01
  • 2011-06-25
  • 2011-04-24
  • 2017-04-23
相关资源
最近更新 更多