避免系统修改转换的时间

下面是伺服器返回的时间戳:

dateFromServer = 2013-07-08 16:45:03Z

下面是转换成NSDate的代码:

    NSDateFormatter *format=[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss'Z'"];
    NSTimeZone *destinationTimeZone=[NSTimeZone systemTimeZone];
    [format setTimeZone:destinationTimeZone];
    dateFromServer=[dateFromServer stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    NSDate*oldTime=[format dateFromString:dateFromServer];

然后获取的结果:

oldTime is 2013-07-08 20:45:03 +0000

看上去给原始的时间戳增加了4

不知道为什么会这样?

这是因为你的时间戳是用协调世界时 (Coordinated Universal Time, UTC) 格式表示的,而你在转换时将其转换为了系统默认时区的时间。


例如,如果你在北京时间下运行代码,北京时间与 UTC 的时差为 8 小时,因此你看到的时间戳会比 UTC 时间早 8 小时。


你可以通过设置日期格式化器的时区为 UTC 来避免这种情况。例如:

[format setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];