古い投稿ですが、他の投稿で見つけたこれを処理するより良い方法があります。
次のような方法を使用できます。
- まず、予想されるいくつかの形式で日付を解析してみます。
- それでもうまくいかない場合は、 を使用
NSDataDetector
して日付情報を検索してみてください (参照:この SO 投稿)。
これに使用したコードのサンプルを次に示します (いくつかの日付形式を期待していましたが、これまでに見た唯一の日付であると確信できず、可能であれば失敗したくありませんでした):
// 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 :(