What types of dates are these?

馋奶兔 提交于 2019-12-18 09:17:53

问题


I have a plist with this format date:

Mar 11, 2013 10:16:31 AM

which shows up in my console as

2013-03-11 16:16:31 +0000

whereas a webservice is returning something that in the console looks like this:

2013-03-01T18:21:45.231Z

How do I fix my plist date to the same format as the web service?


回答1:


Regarding your three date formats:

  1. The first is just the date format when you look at a NSDate in a plist in Xcode, a human readable date in the current locale (but if you look at the plist in a text editor, you'll see it's actually written in @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" format).

  2. The second is the default formatting from the description method a NSDate (e.g. you NSLog a NSDate).

  3. The third is RFC 3339/ISO 8601 format (with fractions of a second), often used in web services.

See Apple's Technical Q&A QA1480.

As an aside, that Technical Note doesn't include the milliseconds, so you might want to use something like @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'", for example:

NSDate *date = [NSDate date];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = enUSPOSIXLocale;
formatter.dateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'";
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSString *dateString = [formatter stringFromDate:date];
NSLog(@"%@", dateString);

You can use this if you want to store the date as a string in RFC 3339/ISO 8601 format in the plist (or alternatively, if you need to convert a NSDate to a string for transmission to your web service). As noted above, the default plist format does not preserve fractions of a second for NSDate objects, so if that's critical, storing dates as strings as generated by the above code can be useful.

And this date formatter can be used for converting dates to strings (using stringFromDate), as well as converting properly formatting strings to NSDate objects (using dateFromString).



来源:https://stackoverflow.com/questions/16046541/what-types-of-dates-are-these

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!