我想将以下NSString
转换为NSDate
:@"2013-04-01T22:00:00Z"
我使用以下代码:
NSString *dateString = @"2013-04-01T22:00:00Z";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *theDate = [dateFormatter dateFromString:dateString];
当我打印theDate
时,我得到以下答案:2013-04-01 20:00:00 +0000
现在我想知道为什么小时是20:00而不是22:00,你有什么想法吗?
谢谢!
答案 0 :(得分:3)
由于您的dateFormat未指定NSDateFormatter
使用您当地时区的时区。你必须自己设置时区。你的字符串中的Z表示GMT。
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
答案 1 :(得分:1)
在您的代码中尝试使用Timezone,我已尝试使用您的默认TImeZone。工作正常。
NSString *dateString = @"2013-04-01T22:00:00Z";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone];
NSDate *theDate = [dateFormatter dateFromString:dateString];