Question

I am trying to use an NSString that contains a date / time, and create an NSDate object out of it so I can manipulate accordingly.

I have used NSDataDetector in the past with no issue. However, when I try it now, detectedDate is returning the current date, as opposed to the date found within the string.

Can someone please explain why this would not return the date from the string as I have used in the past? Or advise how best to achieve this?

Many thanks.

NSString *myDate = @"2014-03-13T12:31:00-07:00";

__block NSDate *detectedDate;

NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
[detector enumerateMatchesInString:myDate
                           options:kNilOptions
                             range:NSMakeRange(0, [myDate length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
 { detectedDate = result.date; } ];
NSLog(@"Result:%@",detectedDate);
Was it helpful?

Solution

See answer from @gaige in comments, who said:-

I ran a quick test on this by removing the "T" from the string and it captured the correct date. Unless you know you're getting an ISO format date in a block of text (as opposed to some formatted data), you are probably OK. For formatted data where you know you're getting a date, I'd suggest Peter Hosey's ISO 8601 NSDateFormatter as an excellent parsing choice.

Thanks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top