This routine will take any string and attempt to parse a valid date string from it
if returns a BOOL (success/fail) and a Date if it succeeded
import Cocoa
import Foundation
public func isValidDate(_ inDATE : String) -> (Bool,Date?) {
let dt = returnDateFromString(inDATE)
if dt == nil { return (false,nil) }
return (true,dt)
}
private func returnDateFromString(_ inDATE: String) -> Date? {
let types : NSTextCheckingResult.CheckingType = [.date ]
let detector = try? NSDataDetector(types: types.rawValue)
var aDate = Date()
let result = detector?.firstMatch(in: inDATE, range: NSMakeRange(0, inDATE.utf16.count))
if result == nil { return nil } // not a valid date
if result?.resultType == .date {
aDate = (result?.date)!
let TZ = Double(TimeZone.current.secondsFromGMT(for: aDate))
aDate = Calendar.current.date(byAdding: .second, value: Int(TZ), to: aDate)!
}
return aDate
}
for example
print( isValidDate("My birthday is 25 jan 56 and it was last month"))
returns
(true, Optional(1956-01-25 12:00:00 +0000))