Possible Duplicate:
Getting date from [NSDate date] off by a few hours
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"M-d-yyyy H:mm"];
NSDate *start= [dateFormatter dateFromString:@"10-24-2012 12:15"];
NSDate *end = [dateFormatter dateFromString:@"10-24-2012 15:30"];
When I print out
NSLog(@"------main_event start %@", start);
NSLog(@"-----main_event end %@", end);
The result is
---main_event start 2012-10-24 19:15:00 +0000
---main_event end 2012-10-24 22:30:00 +0000
Now, it looks like the time added 7 hours automatically, 12:15 becomes 19:15, and 15:30 becomes 22:30.
Why?
because the timezone, where your device is located, is UTC-7.
The output is in UTC (hence the +0000
), as a single NSDate will always print out it's time in UTC.
If you use an NSDateFormatter to output the date, it will take your locale in account. See my answer here: NSDate date method returns wrong result
These are correct results. When you use NSLog
to output an NSDate
object, it displays in GMT. The parsing was done in your local timezone. NSDate
objects are alway in GMT. If you want to print the NSDate object in your local timezone then you need an NSDateFormatter
to print the date.
来源:https://stackoverflow.com/questions/13041200/nsdate-output-incorrectly