問題描述
我有一個具有這種格式日期的 plist:
I have a plist with this format date:
Mar 11, 2013 10:16:31 AM
在我的控制臺中顯示為
2013-03-11 16:16:31 +0000
而 Web 服務正在返回控制臺中的內容,如下所示:
whereas a webservice is returning something that in the console looks like this:
2013-03-01T18:21:45.231Z
如何將我的 plist 日期修復為與 Web 服務相同的格式?
How do I fix my plist date to the same format as the web service?
推薦答案
關于你的三種日期格式:
Regarding your three date formats:
當您在 Xcode 的 plist 中查看
NSDate
時,第一個只是日期格式,這是當前語言環境中人類可讀的日期(但如果您在文本編輯器,你會看到它實際上是用@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
格式編寫的).
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).
第二個是來自 description
方法的默認格式一個 NSDate
(例如你的 NSLog
一個 NSDate代碼>).
The second is the default formatting from the description
method a NSDate
(e.g. you NSLog
a NSDate
).
第三個是RFC 3339/ISO 8601 格式(只有幾分之一秒),通常用于 Web 服務.
The third is RFC 3339/ISO 8601 format (with fractions of a second), often used in web services.
請參閱 Apple 的 技術問答 QA1480.
See Apple's Technical Q&A QA1480.
順便說一句,該技術說明不包括毫秒,因此您可能希望使用類似 @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'"
,例如:
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);
如果您想將日期作為 RFC 3339/ISO 8601 格式的字符串存儲在 plist 中(或者,如果您需要將 NSDate
轉換為字符串以進行傳輸,則可以使用它到您的網絡服務).如上所述,默認的 plist 格式不會為 NSDate
對象保留幾分之一秒,因此如果這很關鍵,將日期存儲為上述代碼生成的字符串可能會很有用.
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.
這個日期格式化程序可用于將日期轉換為字符串(使用 stringFromDate
),以及將正確格式化的字符串轉換為 NSDate
對象(使用 dateFromString
).
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
).
這篇關于這些日期是什么類型的?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!