Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

objective c - NSDateFormatter not giving me correct

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...