iOS NSDateformatter issue - dateFromString does not work properly as expected
The following snippet开发者_开发问答 will give an unexpected output:
Snippet:
NSString* testDateStr = [[NSString alloc] initWithString:@"2010-04-04 19:11:11"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"'%@'", testDateStr);
NSLog(@"'%@'", [dateFormatter dateFromString:testDateStr]);
Output:
'2010-04-04 19:11:11'
'2010-04-04 09:11:11 +0000'
Notice the time hour in date produced is wrong. Is there anything I am doing wrong here?
NSDateFormatter defaults to the local timezone. When you print the description
of the NSDate object, it prints in GMT (notice the +0000 at the end). This code is working exactly as expected. (19:11:11 in your local timezone is the same as 09:11:11 in GMT.)
You can always override the timezone of the NSDateFormatter by calling setTimeZone:
.
The output is not wrong: It looks like you are running in a locale with a GMT + 10 timezone. 19:11:11 in your local timezone is equivalent to 09:11:11 GMT (+0000)
精彩评论