从dateFromString方法的NSDateFormatter获取错误的日期?
问题描述:
我正在尝试从字符串中获取NSDate
对象。我用的是休耕代码从dateFromString方法的NSDateFormatter获取错误的日期?
NSString *[email protected]"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日期是1969-12-31 23点09分00秒+0000
从这种类型的字符串获取NSDate
对象的确切方法是什么?
答
不要立足于NSLoging NSDate
你的结果,因为记录它会给你的时间在GMT 请参阅我的回答对这个问题NSDateFormatter giving me time 4 hours ahead
例如,如果你想在上午4:39到火UILocalNotification
您可以执行以下操作
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;
答
这是正确的。你确实只指定了时间而不是日期。这样,日期被假定为计算机时代1970/1/1(计算机零时间)的开始。 NSLog
然后根据您的时区(GMT-5)显示它。
如果你想得到更好的答案,你必须指定你想要的输出。代码是正确的,结果也是正确的。
+0
我想在今天设置当地通知他有时间 –
我想在今天4:39 AM设置UILocal通知?如何从字符串@“4:39 AM” –
@KAREEMMAHAMMED查看更新后的我是否可以设置开始的答案,如果答案有帮助,请不要忘记接受和/或upvote :) –
感谢您的帮助它对我来说工作得很好 –