从字符串错误地格式化 NSDate
我想从字符串创建 NSDate:
NSString *mostRecentMentionMessageTimestamp = [mostRecentMessage valueForKey:@"updated_at"];
NSLog(@"%@",mostRecentMentionMessageTimestamp);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp];
NSLog(@"%@",mostRecentMentionDate);
当我打印字符串时,它是: 2011-11-10T07:22:59Z
在我从字符串创建日期并打印它后,它是 (null)
我做错了什么?
I would like to create an NSDate from a string:
NSString *mostRecentMentionMessageTimestamp = [mostRecentMessage valueForKey:@"updated_at"];
NSLog(@"%@",mostRecentMentionMessageTimestamp);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp];
NSLog(@"%@",mostRecentMentionDate);
When I print my string it is:
2011-11-10T07:22:59Z
After I make a date from string and print it, it is (null)
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要设置时区并在日期格式末尾删除
Z
。由于您的日期有一个Z
,因此它采用 UTC。所以你可以使用:You need to set the time zone and drop the
Z
at the end of the date format. Since your date has aZ
, it is in UTC. So you can use:格式几乎正确,使用:
解决时区问题使用@Jef add的解决方案:
完整示例代码:
NSLog输出:
The format is almost correct, use:
to solve the time zone issue use the solution by @Jef add:
Full example code:
NSLog output:
您尝试转换为 NSDate 的字符串值不正确。
“2011-11-10T07:22:59Z”
它应该有一个时区差异值来代替“Z”,以使其与日期格式化程序的格式兼容。
例如 2011-11-10T07:22:59+0430
the string value which you are trying to convert to NSDate is incorrect.
"2011-11-10T07:22:59Z"
it should have a timezone difference value in place of "Z" to make it compatible to date formatter's format.
e.g. 2011-11-10T07:22:59+0430