这些日期是什么类型的? [英] What types of dates are these?

查看:6

问题描述

我有一个具有这种格式日期的 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:

  1. 当您在 Xcode 的 plist 中查看 NSDate 时,第一个只是日期格式,这是当前语言环境中人类可读的日期(但如果您在文本编辑器,你会看到它实际上是用 @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'" 格式编写的).

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

第二个是来自 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).

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆