[英]Getting wrong date from NSDateFormatter from dateFromString Method?
I am trying to get NSDate
object from string . 我正在尝试从string获取
NSDate
对象。 I use the fallowing code 我使用休闲代码
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);
But it gives wrong output such like as 但是它给出了错误的输出,例如
Date from string 4:39 AM is 1969-12-31 23:09:00 +0000 来自字符串4:39 AM的日期是1969-12-31 23:09:00 +0000
What is the exact way to get the NSDate
object from this type of strings. 从这种类型的字符串获取
NSDate
对象的确切方法是什么。
Dont base your result on NSLoging NSDate
, since logging it will give you the time in GMT Please refer to my answer on this question NSDateFormatter giving me time 4 hours ahead 不要将结果记录在NSLoging
NSDate
,因为记录它会为您提供格林尼治标准时间的时间。请参考我对这个问题的回答NSDateFormatter,让我提前4小时
For example if you want to fire a UILocalNotification
at 4:39 am you would do the following 例如,如果您想在凌晨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;
This is correct. 这是对的。 You did specify only time and not date.
您确实只指定了时间而不指定了日期。 This way, date is assumed to be the beginning of computer age 1970/1/1 (computer zero time).
这样,日期被假定为计算机年龄1970/1/1(计算机零时间)的开始。
NSLog
then shows it depending on your time zone (GMT-5). 然后,
NSLog
会根据您的时区(GMT-5)显示它。
If you want a better answer, you have to specify what output you want. 如果想要更好的答案,则必须指定所需的输出。 The code is correct ant the result is correct, too.
代码是正确的,结果也是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.