简体   繁体   English

在 cocoa 中解析 ISO8601 日期的正确方法是什么?

[英]What's the right way to parse an ISO8601 date in cocoa?

I would like to parse ISO8601 dates in Cocoa, both for iOS 4+ and OSX 10.6+我想为 iOS 4+ 和 OSX 10.6+ 解析 Cocoa 中的 ISO8601 日期

There are a few questions about this on StackOverflow already, but in my opinion none of them contain good answers. StackOverflow 上已经有一些关于此的问题,但在我看来,没有一个包含好的答案。 Here's what I think constitutes a good answer:我认为这是一个很好的答案:

  1. The answer should point to code with support for ISO8601.答案应该指向支持 ISO8601 的代码。 This code should compile cleanly under XCode 4 for both iOS 4+ and OSX 10.6+.对于 iOS 4+ 和 OSX 10.6+,此代码应在 XCode 4 下干净地编译。

  2. The code should support all possible ISO8601 date formats.该代码应支持所有可能的 ISO8601 日期格式。

    Please note that there are many, many possibilities here.请注意,这里有很多很多的可能性。 Simply answering with one or two format strings for NSDateFormatter is not going to cut it.简单地用NSDateFormatter的一两个格式字符串回答并不会减少它。

  3. The answer should not be this library .答案应该是这个库 That's because it is riddled with dangerous 32-bit assumptions, it's far more complicated than necessary, and it doesn't compile clean with XCode4/Clang.那是因为它充满了危险的 32 位假设,它比必要的复杂得多,而且它不能用 XCode4/Clang 编译干净。 Bottom line: I don't trust it at all!底线:我根本不相信它!

Thanks, fellow Cocoa-ites.谢谢,可可们。 I'm excited to find out if there's a real answer here!我很高兴知道这里是否有真正的答案!

The best way is this library .最好的方法是这个库

I should add a link on that page to the Bitbucket repo , which contains newer source code (including 32-bit and Clang fixes.) and has an issue tracker, If you find any other bugs in it.我应该在该页面上添加一个指向Bitbucket 存储库的链接,其中包含更新的源代码(包括 32 位和 Clang 修复程序。)并且有一个问题跟踪器,如果您在其中发现任何其他错误。 please file them.请归档。

I'd also like to know what you mean by “more complicated than necessary”.我也想知道你所说的“比必要的更复杂”是什么意思。 Normal usage is very simple:正常使用很简单:

ISO8601DateFormatter *formatter = [[[ISO8601DateFormatter alloc] init] autorelease]; //Or, if you prefer, create it once in -init and own it until -dealloc 
NSDate *parsedDate = [formatter dateFromString:inString];
NSString *unparsedString = [formatter stringFromDate:inDate];

You can switch out dateFromString: or stringFromDate: for one of the longer methods if you need more information (eg, to preserve the time zone).如果您需要更多信息(例如,保留时区),您可以将dateFromString:stringFromDate:较长的方法之一。

If you mean something else, I want to hear it so I can improve the library.如果你的意思是别的,我想听听,这样我就可以改进图书馆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM