objective c - NSDateFormatter 输出不正确

objective c - NSDateFormatter incorrect output

为什么下面的代码转换后输出不正确的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

提前致谢。

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