如果我不知道格式,如何使用 iPhone SDK 解析表示日期和/或时间的字符串?我正在构建一个允许使用一系列可能的日期和时间的应用程序,并且我不希望它失败,因为格式是“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 中做到这一点。
最佳答案
旧帖子,但我在其他帖子中找到了更好的方法来处理这个问题。
您可以使用这样的方法:
- 首先,尝试以几种预期格式解析日期。
- 如果这不起作用,请使用
NSDataDetector
尝试查找日期信息(引用: this SO post )。
这是我用于此目的的代码示例(我期望有几种日期格式,但无法确定这是我见过的唯一日期,并且如果可能的话不想失败):
// 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 :(
关于iphone - 如何在 iPhone 上解析未知格式的日期字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3485209/