从 NSString 转换为 NSDate(即使你不知道 NSString 格式)

发布于 2024-08-23 22:37:52 字数 328 浏览 4 评论 0原文

我有一个 NSString,可能包含 5-10 个不同样式的日期和时间。 我需要将它们全部转换为 NSDate。

iPhone SDK 3.1.3 中不再存在 dateWithNaturalLanguageString 吗?

不需要需要转换@“上周三下午 1 点”之类的内容。

我需要转换如下内容: @“2010 年 2 月 1 日” @“2010 年 2 月 1 日” @“2010年2月1日” @“2010年12月31日” @“12-31-2010”

(我见过的每个示例都要求您已经知道 NSString 的格式。我知道它会是什么格式。)

I have an NSString that might contain 5-10 different style dates and times.
I need to convert all of them into NSDates.

Does dateWithNaturalLanguageString no longer exist in iPhone SDK 3.1.3?

I do NOT need to convert things like @"last Wednesday at 1 pm".

I need to convert things like:
@"01-Feb-2010"
@"Feb 1, 2010"
@"February 1, 2010"
@"12/31/2010"
@"12-31-2010"

(Every example I've seen requires that you already KNOW the format of the NSString. I have NO idea what format it will be.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

み青杉依旧 2024-08-30 22:37:52

您知道所有可能的格式吗?您始终可以尝试为每个创建一个 NSDateFormatter,然后尝试一个字符串,直到返回有效日期。这相当笨拙,但可能比什么都没有好。

Do you know all of the possible formats? You could always try creating an NSDateFormatter for each one, then trying a string until a valid date is returned. That's pretty kludgy, but might be better than nothing.

治碍 2024-08-30 22:37:52

我在任何 iPhone SDK 版本中都没有看到 dateWithNaturalLanguageString;这可能是旧版本文档中的一个错误(Mac OS X 中的等效功能在 10.4 中已被弃用,并且无论如何都不能很好地工作)。

相反,只需尝试依次解析每种不同的日期格式即可。

实现自然语言日期解析,特别是以适用于每个语言环境的方式,是非常困难的。如果您需要在其他上下文中进行自然语言日期解析,我发现的最好的方法是 Date ::Manip Perl 模块。

I don't see dateWithNaturalLanguageString in any iPhone SDK version; it was probably an error in an older version of the documentation (the equivalent functionality in Mac OS X was deprecated in 10.4 and never worked very well anyway).

Instead, just try parsing with each of the various date formats in turn.

Implementing natural-language date parsing, particularly in a way that works for every locale, is very hard. If you need natural-language date parsing in another context, the best I've found is the Date::Manip Perl module.

就像说晚安 2024-08-30 22:37:52

您应该始终使用 NSDataDetector,因为它可以很好地处理未知格式,请参阅:

使用 NSDataDetector 进行 NSDate 检测

You should always use a NSDataDetector as it handles unknown formats really well, see this:

NSDate detection with NSDataDetector

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文