Search code examples
objective-cparsingdatetimeios7nsdatadetector

Detecting a duration via NSDataDetector


I'm trying to use NSDataDetector to detect different data in strings. I noticed that when detecting a date (i.e. resultType is NSTextCheckingTypeDate), there are three valid properties:

  • date
  • duration
  • timeZone

I was able to figure out how to create strings that produce a value for the date and timeZone, but I'm not sure which string will produce a value for duration.

For example, when I try parsing 12:15 UTC, it populates the date and timeZone. I was thinking that something like 10 minutes would produce a value for duration, but it doesn't even produce a match.

Note: duration should work according to NSHipster and Apple. Notice how in the NSTextCheckingResult documentation, there is a section titled Text Checking Results for Dates and Times which mentions duration.


Solution

  • You'll get a duration if Data Detectors detects a date interval. For example with this string: "from December 10th at 2 to December 12th at 1"

    and this logging code:

    NSLog(@"Match: %@ (duration %g)", result, result.duration);
    

    I get:

    Match: <NSDateCheckingResult: 0x7fc2da810830>{0, 45}{2014-12-10 13:00:00 +0000-2014-12-12 12:00:00 +0000} (duration 169200)
    

    (I'm in the UTC+1 timezone, this is why the hours are offset in the result)