如何在iPhone上以未知格式的日期字符串解析?
-
28-09-2019 - |
题
如果我不知道格式,我该如何解析代表日期和/或时间使用时间和时间的字符串?我正在构建一个应用程序,该应用程序将允许使用一系列可能的日期和时间,并且我不希望它失败,因为格式为“ 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中做到这一点。
解决方案
很遗憾, NSDateFormatter
在iPhone上不是 那 聪明的。您需要给它一些指导。当您将日期和时间样式设置为 NoStyle
它预计不会看到日期也没有时间。您将至少需要其中一种设置为其他样式。您可以做类似以下操作的事情,它应该可以正常工作(对我来说确实可以)。
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterNoStyle];
[formatter setLenient:YES];
NSDate * date = [formatter dateFromString:@"01-01/2001"];
NSLog(@"%@", date);
其他提示
旧帖子,但是有更好的方法可以处理其他帖子。
您可以使用这样的方法:
- 首先,尝试以几种预期格式解析日期。
- 如果那不起作用,请使用
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 :(
您的潜在解析器将如何确定10/02/10是否是2010年1月2日; 2010年2月1日;还是完全不同的东西? bboth mm/dd/yy和dd/mm/yy是合理的,具体取决于客户的位置。
不隶属于 StackOverflow