如何在 iPhone 上解析未知格式的日期字符串?

发布于 2024-09-14 20:31:01 字数 379 浏览 4 评论 0原文

如果我不知道格式,如何使用 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 技术交流群。

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

发布评论

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

评论(3

浪漫之都 2024-09-21 20:31:01

老帖子,但我在其他帖子中找到了更好的方法来处理这个问题。

您可以使用这样的方法:

  • 首先,尝试以几种预期的格式解析日期。
  • 如果这不起作用,请使用 NSDataDetector 尝试查找日期信息(参考:这篇文章)。

这是我用于此目的的代码示例(我期望有几种日期格式,但无法确定这是我见过的唯一日期,并且如果可能的话不想失败):

// your date formats may vary, the OP might try "MM/dd/yyyy" and "MM-dd-yyyy", along with combos that include time info
NSArray *dateFormatsToTry = @[@"yyyy-MM-dd'T'HH:mmZZZZ", @"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

for (NSString * format in dateFormatsToTry) {
    [dateFormatter setDateFormat:format];
    NSDate *date = [[[self class] sharedDateFormatter] dateFromString:dateString];
    if (date) {
        return date;
    }
}

// try and figure out the date if the all of the expected formats failed to
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:nil];
NSTextCheckingResult *result = [detector firstMatchInString:dateString options:0 range:NSMakeRange(0, [dateString length])];
if ([result resultType] == NSTextCheckingTypeDate) {
    NSDate * date = [result date];
    if (date) {
        return date;
    }
}

return [NSDate date]; // default to now :(

Old post, but there are better ways to handle this that I found on other posts.

You can use a method like this:

  • First, try and parse the date in a couple of expected formats.
  • If that doesn't work, use 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):

// your date formats may vary, the OP might try "MM/dd/yyyy" and "MM-dd-yyyy", along with combos that include time info
NSArray *dateFormatsToTry = @[@"yyyy-MM-dd'T'HH:mmZZZZ", @"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

for (NSString * format in dateFormatsToTry) {
    [dateFormatter setDateFormat:format];
    NSDate *date = [[[self class] sharedDateFormatter] dateFromString:dateString];
    if (date) {
        return date;
    }
}

// try and figure out the date if the all of the expected formats failed to
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:nil];
NSTextCheckingResult *result = [detector firstMatchInString:dateString options:0 range:NSMakeRange(0, [dateString length])];
if ([result resultType] == NSTextCheckingTypeDate) {
    NSDate * date = [result date];
    if (date) {
        return date;
    }
}

return [NSDate date]; // default to now :(
我是有多爱你 2024-09-21 20:31:01

不幸的是,iPhone 上的 NSDateFormatter 并不那么智能。你需要给它一点指导。当您将日期和时间样式都设置为 NoStyle 时,它不会看到日期或时间。您至少需要将其中一个设置为其他样式。你可以做类似下面的事情,它应该可以正常工作(对我来说是这样)。

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLenient:YES];

NSDate * date = [formatter dateFromString:@"01-01/2001"];

NSLog(@"%@", date);

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

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLenient:YES];

NSDate * date = [formatter dateFromString:@"01-01/2001"];

NSLog(@"%@", date);
北城孤痞 2024-09-21 20:31:01

您的潜在解析器将如何确定 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.

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