objective-c之从 dateFromString 方法的 NSDateFormatter 获取错误的日期

无情 阅读:72 2025-06-02 22:19:02 评论:0

我正在尝试获取 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; 


标签:日期
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号