9

我试图从具有UNKNOWN格式的 NSString 中获取 NSDate,所以我编写了一个如下所示的函数

-(void)dateFromString:(NSString*)string {

    NSError *error = NULL;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:(NSTextCheckingTypes)NSTextCheckingTypeDate error:&error];

    NSArray *matches = [detector matchesInString:string
                                         options:0
                                           range:NSMakeRange(0, [string length])];

    NSLocale* currentLoc = [NSLocale currentLocale];
    for (NSTextCheckingResult *match in matches) {
        if ([match resultType] == NSTextCheckingTypeDate) {
            NSLog(@"Date : %@", [[match date] descriptionWithLocale:currentLoc]);
        }
    }
}

它运作良好,除了一个地方。

如果我调用

[self dateFromString:@"6/12"];

它打印

日期:澳大利亚东部标准时间 2014 年6 月 12日星期四下午 12:00:00

同时,如果我打电话

[self dateFromString:@"13/12"];

它打印

日期:澳大利亚东部夏令时间 2013 年12 月 13日星期五下午 12:00:00

基本上,我希望函数表现一致。由于我住在澳大利亚,它应该在 12 月 6 日返回第一次执行。第二次调用结果是正确的。

我在这里做错了什么?

4

2 回答 2

6

实际上,我写的方法效果很好:)。不幸的是,我的测试手机中的区域格式设置为美国并且从未设置回澳大利亚:我的坏..

@joiningss:向这些方法中添加一些随机格式化的日期字符串,您会惊讶于苹果如何让开发人员轻松使用。无论如何,非常感谢你。

@mrt,Chavda&Greg:非常感谢大家。我真的很感谢你的帮助。

于 2013-12-06T13:35:55.420 回答
0

你必须使用 NSDateFormatter。尝试将您的 if 语句替换为:

if ([match resultType] == NSTextCheckingTypeDate) {
   NSDate *dateAfter = [match date];
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
   [dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];
   NSString *formattedDateString = [dateFormatter stringFromDate:dateAfter];
   NSLog(@"After: %@", formattedDateString);
}

如果你想以不同的格式显示它,你必须将此行更改为所需的格式:

[dateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"];

如果您希望它与您的第一个示例匹配,请将其更改为:

[dateFormatter setDateFormat:@"EEEE, MMMM dd, yyyy 'at' HH:mm:ss a zzzz"];
于 2013-12-06T08:50:53.787 回答