我正在尝试获取 NSDate
来自字符串的对象。我使用休闲代码
NSString *st1=@"4:39 AM";
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a"];
NSDate *dateobj=[dateFormatter dateFromString:st1];
NSLog(@"Date from string 4:39 AM is %@",dateobj);
但它给出了错误的输出,例如
来自字符串 4:39 AM 的日期是 1969-12-31 23:09:00 +0000
获取
NSDate
的确切方法是什么?来自这种类型的字符串的对象。
最佳答案
不要将结果基于 NSLoging NSDate
,因为记录它会给你格林威治标准时间
请引用我对这个问题的回答 NSDateFormatter giving me time 4 hours ahead
例如,如果您想触发 UILocalNotification
在凌晨 4:39,您将执行以下操作
NSCalendar* myCalendar = [NSCalendar currentCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
//4:39 Am
[components setHour: 4]; //4 am
[components setMinute: 39];//39 minutes
[components setSecond: 0];// 0 seconds
NSDate *myDate = [myCalendar dateFromComponents:components];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd, yyyy h:mma"];
NSString *str = [formatter stringFromDate:myDate];
NSLog(@"date is %@", myDate); //This will log the correct data but in GMT time zone
NSLog(@"date is %@", str); //This will log the correct data
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = myDate;
关于objective-c - 从 dateFromString 方法的 NSDateFormatter 获取错误的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10977133/