为什么以下代码在转换后输出错误的Date
?
NSString *customDate = @"23-06-1993";
NSLog(@"Custom Date: %@", customDate);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *birthDayDate = [formatter dateFromString:customDate];
NSLog(@"After Conversion: %@", birthDayDate);
输出:
Custom Date: 20-12-1993
After Conversion: 1993-12-19 16:00:00 +0000
提前致谢。
答案 0 :(得分:-4)
NSDateFormatter
会使用您当前的时区(GMT + 8)。您应该将格式化程序的时区设置为UTC
(换句话说,GMT)以正确格式化日期。
NSLog(@"Current timezone: %@", [NSTimeZone defaultTimeZone]);
NSString *customDate = @"23-06-1993";
NSLog(@"Custom Date: %@", customDate);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *utcDate = [formatter dateFromString:customDate];
NSLog(@"After Conversion: %@", utcDate);
Custom Date: 23-06-1993
After Conversion: 1993-06-23 00:00:00 +0000