使用NSDataDetector进行NSDate检测 [英] NSDate detection with NSDataDetector
问题描述
我试图用 UNKNOWN 格式从NSString获取NSDate,所以我写了一个类似下面的函数
I tried to get a NSDate from a NSString with UNKNOWN format, So I wrote a function like below
-(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"];
打印
日期:星期四, 6月12日,2014年00:00:00 PM澳大利亚东部
标准时间
Date : Thursday, June 12, 2014 at 12:00:00 PM Australian Eastern Standard Time
同时如果我打电话
[self dateFromString:@"13/12"];
打印
日期:星期五, 12月13日,2013年12:00:00 PM澳大利亚东部
日光时间
Date : Friday, December 13, 2013 at 12:00:00 PM Australian Eastern Daylight Time
基本上,我希望函数表现一致。由于我住在澳大利亚,它应该在12月6日首次执行。第二个通话结果是正确的。
Basically, I want the function to behave consistent. Since I live in Australia, it should have returned December 6 for the first execution. Second call result is correct.
我在这里做错了什么?
推荐答案
实际上,我写的方法效果很好:)。不幸的是,我的测试手机中的区域格式设置为美国,并且从未回到澳大利亚:我的不好......
Actually, the method I wrote works really well :). Unfortunately, the Region Format in my test phone was set to US and was never set back to Australia : My bad..
@joiningss:将一些随机格式化的日期字符串丢到那些方法和你会惊讶,苹果如何让开发人员轻松。无论如何,非常感谢你。
@joiningss : Throw some random formatted date string to that methods and you will be amazed, how apple has made it easy for developers. Anyway, thank you so much.
@ mrt,Chavda& Greg:非常感谢你们。非常感谢你的帮助。
@mrt,Chavda&Greg : Thanks a lot guys. I really appreciate your help.
这篇关于使用NSDataDetector进行NSDate检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!