日期格式从日期出错

时间:2011-07-05 08:24:50

标签: iphone objective-c ios cocoa-touch

NSLog(@"Time From DB %@", mytime.beginTime);     
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"hh:mm a"];
UILabel *timeLabel = (UILabel *)[cell viewWithTag:1];
timeLabel.text = [timeFormatter stringFromDate:mytime.beginTime];
NSLog(@"Time after formatting %@", timeLabel.text);
[timeFormatter release];

控制台

2011-07-05 11:16:09.331 My project[1907:207] Time From DB 2011-05-10 13:54:09 +0000
2011-07-05 11:16:09.331 My project[1907:207] Time after formatting 04:54 PM

为什么时代不同?如何解决?

2 个答案:

答案 0 :(得分:5)

正在使用用户的时区(默认)。如果你想要它在GMT中,你将必须设置日期格式化程序的时区。

[timeFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
顺便说一下BTW时代并没有什么不同。时间是相同的,但在不同的时区表现出来。

答案 1 :(得分:2)

日期 2011-05-10 13:54:09 +0000 的值在 GMT 时区,您可以从 +中注意到这一点0000 的日期。因此,在转换时,日期格式化程序会使用手机的时区,即您所在位置的时区,即 -03:00 。因此,为了将GMT时区中的日期转换为GMT时区日期,如果GMT不是手机的默认时区,则需要将日期格式器的时区明确设置为GMT,如@ Deepak的答案中所述。

相关问题