我想从字符串创建一个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)
我做错了什么?
答案 0 :(得分:1)
您需要设置时区并将Z
放在日期格式的末尾。由于您的日期为Z
,因此为UTC。所以你可以使用:
[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]];
[dateFormatter setDateFormat: @"yyyy-MM-dd'T'HH:mm:ss"];
答案 1 :(得分:0)
您尝试转换为NSDate的字符串值不正确。
“2011-11-10T07:22:59Z”
它应该有一个时区差值代替“Z”,以使其与日期格式化程序的格式兼容。
例如2011-11-10T07:22:59 + 0430
答案 2 :(得分:0)
格式几乎正确,请使用:
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
解决时区问题使用@Jef添加的解决方案:
[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]];
完整的示例代码:
NSString *mostRecentMentionMessageTimestamp = @"2011-11-10T07:22:59Z";
NSLog(@"input: %@",mostRecentMentionMessageTimestamp);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone: [NSTimeZone timeZoneWithAbbreviation: @"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *mostRecentMentionDate = [dateFormatter dateFromString:mostRecentMentionMessageTimestamp];
NSLog(@"output: %@",mostRecentMentionDate);
NSLog输出:
input: 2011-11-10T07:22:59Z
output: 2011-11-10 07:22:59 +0000