我试图从具有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 日返回第一次执行。第二次调用结果是正确的。
我在这里做错了什么?