如何在 iPhone 上解析未知格式的日期字符串?
如果我不知道格式,如何使用 iPhone SDK 解析表示日期和/或时间的字符串?我正在构建一个允许使用一系列可能的日期和时间的应用程序,我不希望它失败,因为格式是“01/01/2001”而不是“01-01-2001”等时间可能包括也可能不包括。
有什么办法可以做到这一点吗?我尝试使用 NSDateFormatter 将日期和时间样式设置为“NoStyle”,并且 setLenient = YES,但它仍然无法解析最简单的字符串:“1/22/2009 12:00:00 PM”
我无法提前知道格式,我需要一种可以启发式确定格式的方法。
我来自 .NET 背景,这就像 new DateTime(string_in_any_format); 一样简单但我不知道如何在 Obj-C 中做到这一点。
How can I parse a string that represents a date and/or time using iPhone SDK if I do not know the format? I am building an application that will allow a range of possible dates and times to be used, and I don't want it to fail because the format was "01/01/2001" instead of "01-01-2001", etc. Time may or may not be included.
Is there any way to do this? I have tried using NSDateFormatter with date and time styles set to "NoStyle", and setLenient = YES, but it still fails to parse the simplest of strings: "1/22/2009 12:00:00 PM"
I have no way of knowing the format in advance, I need a method that will heuristically determine the format.
I am coming from a .NET background, where this is as simple as new DateTime(string_in_any_format); but I have no idea how to do this in Obj-C.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
老帖子,但我在其他帖子中找到了更好的方法来处理这个问题。
您可以使用这样的方法:
这是我用于此目的的代码示例(我期望有几种日期格式,但无法确定这是我见过的唯一日期,并且如果可能的话不想失败):
Old post, but there are better ways to handle this that I found on other posts.
You can use a method like this:
NSDataDetector
to try and find date information (reference: this SO post).Here's a sample of code I used for this (I expected a couple date formats, but couldn't be certain that's the only date I'd ever see and didn't want to fail if possible):
不幸的是,iPhone 上的
NSDateFormatter
并不那么智能。你需要给它一点指导。当您将日期和时间样式都设置为NoStyle
时,它不会看到日期或时间。您至少需要将其中一个设置为其他样式。你可以做类似下面的事情,它应该可以正常工作(对我来说是这样)。Unfortunately,
NSDateFormatter
on the iPhone isn't that smart. You need to give it a little guidance. When you set both the date and time styles toNoStyle
it expects to see neither a date nor time. You'll need at least one of them set to some other style. You can do something like the following and it should work fine (it does for me).您的潜在解析器将如何确定 01/02/10 是否为 2010 年 1 月 2 日; 2010 年 2 月 1 日;或者完全不同的东西? mm/dd/yy 和 dd/mm/yy 都是合理的预期,具体取决于您的客户所在的位置。
How would your potential parser determine if 01/02/10 is jan 2, 2010; feb 1, 2010; or something entirely different? Bboth mm/dd/yy and dd/mm/yy are reasonable to expect, depending on where your customers are.