将 NSDate 的描述转换为 NSDate?
我将我的 NSDate 存储到一个文件中,该文件采用国际格式,当您在 NSDate 上调用描述时会得到该文件。
但是,我不知道如何从字符串格式返回到 NSDate 对象。 NSDateFormatter 似乎仅限于几种格式,不包括国际格式。
我应该如何从字符串格式返回?
I store my NSDates to a file in the international format you get when you call description on a NSDate.
However, I don't know how to go back from the string-format to an NSDate object. NSDateFormatter seems to be limited to a couple of formats not including the international one.
How should I go back from the string-format?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Jeff 是对的,
NSCoding
可能是序列化NSDate
对象的首选方式。无论如何,如果您确实想要/需要将日期保存为纯日期字符串,这可能会帮助您:实际上,
NSDateFormatter
根本不限于预定义的格式。您可以通过 dateFormat 属性设置任意自定义格式。以下代码应该能够解析“国际格式”的日期字符串,即。格式NSDate
的-description
使用:有关格式字符串语法的完整参考,请查看 Unicode 标准。
但是,请小心
-description
- 这些方法的输出通常是针对人类读者的(例如日志消息),并且不能保证它不会在新的 SDK 中更改其输出格式版本!您应该使用相同的日期格式化程序来序列化日期对象:Jeff is right,
NSCoding
is probably the preferred way to serializeNSDate
objects. Anyways, if your really want/need to save the date as a plain date string this might help you:Actually,
NSDateFormatter
isn't limited to the predefined formats at all. You can set an arbitrary custom format via thedateFormat
property. The following code should be able to parse date strings in the "international format", ie. the formatNSDate
's-description
uses:For a full reference on the format string syntax, have a look at the Unicode standard.
However, be careful with
-description
- the output of these methods is usually targeted to human readers (eg. log messages) and it is not guaranteed that it won't change its output format in a new SDK version! You should rather use the same date formatter to serialize your date object:与其将描述保存到文件中,为什么不保存对象本身呢?
NSDate
符合NSCoding
协议;保存对象意味着您不必担心翻译它。有关详细信息,请参阅 NSCoding 协议参考 。Instead of saving the description to a file, why not save the object itself?
NSDate
conforms to theNSCoding
protocol; saving the object means you don't have to worry about translating it. See the NSCoding protocol reference for more information.我会尝试设置一个
NSDateFormatter
通过以下方法成功解析字符串:请注意,您可能需要一段时间才能成功设置
NSDateFormatter
解析你的字符串。如果您要像这样存储面向程序的数据,我还建议将其存储为更易于访问的格式,例如
CFAbsoluteTime
。一旦将其放入程序中,您就可以将其格式化为国际格式或其他人类可读的格式。I would try to set up an
NSDateFormatter
to successfully parse the string by the following method:Note that it could take you a while to get the
NSDateFormatter
set up just right to successfully parse your string.If you're going to store program-facing data like this I would also recommend storing it in an easier-to-access format, e.g.,
CFAbsoluteTime
. Once you have it in your program you can format it into the international format or something else human-readable.将其转换为 NSDate 接受的格式,然后执行转换回来。
或者,根据您所指的 NSDate (!) initWithString 应该涵盖国际标准日期。
Convert it to a format NSDate accepts and then perform the conversion back.
Alternatively, depending on which NSDate you're referring to (!) initWithString should cover international standard dates.