2

I encountered a somewhat not expected result when analysing string for date with NSDataDetector: I admit, lazy me finds it easier to parse that way, rather than trying to pick dates inside the string : it works in most languages, and you need not know the actual format. It is really efficient, it will indeed pick the first date it finds (and if the string describes a period, you'd be able to find duration as another match!).

…Unless the string describes a period over Dec 31st, and longer than about 2 month, like "from December 1 to March 1", then it picks the end date !
When "from December 1 to February 1" would return the first date ! Any clue ?

(Below code is not handling error, and, yes, is on purpose picking first match, which happens normally to be the first found date)

func returnDateFromString( text: String) -> Date {
    let types: NSTextCheckingResult.CheckingType = [.date ]
    let detector = try? NSDataDetector(types: types.rawValue)
    var aDate = Date() // default to today if none, no error check I know 
    let result = detector?.firstMatch(in: text, range: NSMakeRange(0, text.utf16.count))
    if result?.resultType == .date {
        aDate = (result?.date)!
  }
return aDate
}

returnDateFromString(text: "from December 1 to February 1") // returns "Dec 1, 2017, 12:00 PM"
returnDateFromString(text: "from December 1 to March 1") // returns "Mar 1, 2017, 12:00 PM"
XavBart
  • 21
  • 3

0 Answers0