Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ios - What types of dates are these?

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...