NSDataDetector can't detect date nor time in "2014-11-21T08:05:16+0400"

362 Views Asked by At

(this applies to OSX, have not tested on iOS)

Before you ask 'why such a silly date format': I use meta data pulled from files created on the iPhone/iPad. Photos and videos contain a 'creationDate' Metadata Tag that returns an NSString in exactly this format. Now if I feed this string:

@"2014-11-21T08:05:16+0400"

into NSDateDetector the following way:

__block NSDate *detectedDate;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:nil];
[detector enumerateMatchesInString:self
                           options:kNilOptions
                             range:NSMakeRange(0, [self length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)

 { detectedDate = result.date; }];

 NSLog(detectedDate.description);

I receive a completely bogus value:

"2014-12-12 14:16:00 CET"

  • The date "2014-12-12" is today's date, not 2014-11-21 as it should
  • The time "14:16:00 CET" is complete fracked, not even the time the code ran

So we have at least two possibilities here - basically NSDateDetector can't process the standard format Apple encodes dates on the iPhone OR I've made an obvious error in my code that I can't find. I'd be happy if the second was true, so can you tell me what I'm doing wrong?

Oh, I'm running this on Mavericks / XCode 5. Anyone? Please? -ch

1

There are 1 best solutions below

2
Julien On

NSDataDetector is not meant to parse dates like that. Data detectors are meant to detect "human" patterns in written text.

If you want to parse dates, you should use NSDateFormatter.