【问题标题】:objective c - NSDateFormatter incorrect output [duplicate]目标c-NSDateFormatter输出不正确[重复]
【发布时间】:2015-05-11 10:29:51
【问题描述】:

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

提前致谢。

【问题讨论】:

标签: objective-c xcode nsdate nsdateformatter


【解决方案1】:

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

【讨论】:

  • 这是错误的。将时区更改为 UTC 将更改实际日期,副作用是通过 [date description] 打印时日期现在看起来正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多