【发布时间】:2013-12-23 12:10:09
【问题描述】:
我试图从 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 日返回第一次执行。第二次调用结果正确。
我在这里做错了什么?
【问题讨论】:
-
你为什么不使用NSDateFormatter,它很灵活,你可以很容易地解决你的问题,因为你可以设置日期字符串的格式。您使用 setDateFormat 设置日期格式,然后调用 dateFromString: 将字符串转换为日期
-
我认为没有处理 UNKNOWN 格式日期字符串的好方法。您应该确定日期字符串的格式
-
难以置信,我的谷歌搜索如何让我找到我正在寻找的东西,伙计:)
标签: ios objective-c nsdate nsregularexpression nsdatadetector