1

我正在尝试NSDate从 string 获取对象。我使用休闲代码

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从这种类型的字符串中获取对象的确切方法是什么。

4

2 回答 2

4

不要将你的结果基于 NSLoging NSDate,因为记录它会给你 GMT 的时间 请参考我对这个问题的回答NSDateFormatter 给我提前 4 小时的时间

例如,如果您想UILocalNotification在凌晨 4:39 触发 a,您可以执行以下操作

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;
于 2012-06-11T09:09:22.663 回答
2

这是对的。您确实只指定了时间而不是日期。这样,日期被假定为计算机时代 1970/1/1(计算机零时间)的开始。NSLog然后根据您的时区 (GMT-5) 显示它。

如果你想要一个更好的答案,你必须指定你想要的输出。代码是正确的,结果也是正确的。

于 2012-06-11T09:15:42.050 回答