简体   繁体   中英

NSDateFormatter, NSDate, UTC and strange date format

I have a very strange date format coming to me via JSON. eg - "July, 18 2010 02:22:09"

These dates are always UTC. I'm parsing the date with NSDateFormatter, and setting the timeZone to UTC...

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[inputFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
[inputFormatter setDateFormat:@"MMMM, dd yyyy HH:mm:ss"];
NSDate *formatterDate = [inputFormatter dateFromString:dtStr];

However, the date when logged is appearing with the offset of my device...

"2010-07-18 02:22:09 -0600"

What am I doing wrong here?

I think this is because your NSDate isn't using the UTC timezone. The docs say this about the description method of NSDate:

A string representation of the receiver in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”).

So, you aren't really doing anything wrong. NSDate is behaving as expected. What are you trying to accomplish? Do you need the date in a string? Are you doing date comparison?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM