NSDateFormatter没有给我正确的答案

问题描述:

我正在显示时间。它会告诉我:时间:2012-06-18 23:00:00 +0000
但是在使用NSDateFormatter之后我不知道为什么它会给我00:00:00 AM

I am displaying time. It will show me :TIME :2012-06-18 23:00:00 +0000 But after using NSDateFormatter I do not know why it is giving me 00:00:00 AM

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"HH:mm:ss a"];

NSLog(@"TIME :%@",self.startDate);

NSDate *date = [NSDate date];
NSString * _startTime = [dateFormatter stringFromDate:date];
NSLog(@"current time : %@",_startTime);
NSString * _startTime1 = [dateFormatter stringFromDate:self.startDate];
NSLog(@"Start time : %@",_startTime1);
[dateFormatter release];

**Result is**

TIME :2012-06-18 23:00:00 +0000
current time : 17:05:41 PM
Start time : 00:00:00 AM


您的第一个 NSLog 以GMT时间输出日期(请注意尾随的+0000)。 NSDateFormatter 对象将日期格式化为指定的时区。您的 NSLog 语句显示 self.startDate 中存储的日期恰好是00:00:00 AM至少一个时区,格式化程序设置为该时区。格式化程序将默认为设备的时区。您可以将格式化板的时区设置为从GMT到0秒,从上一个 NSLog 语句中看到23:00:00 PM:

Your first NSLog outputs the date in GMT time (notice the trailing +0000). An NSDateFormatter object will format the date to the specified time zone. Your NSLog statements show that the stored date in self.startDate is exactly 00:00:00 AM in at least one time zone, and the formatter is set to that time zone. The formatter will default to the time zone for the device. You could set the formatter's timezone to 0 seconds from GMT to see 23:00:00 PM out of your last NSLog statement:

[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];