i have data contains date string.
normally in 'jan. 3, 1966' type format, because of international differences, may not that.
i need read data in , convert standard date string ('yyyy-mm-dd').
basically have far:
var datastring = 'jan. 3, 1966' var dateformatter = nsdateformatter() dateformatter.dateformat = # don't know exact input format ! let datevalue = dateformatter.datefromstring(datastring)
xcode 9 • swift 4 or xcode 8.3.2 • swift 3.1
you can use nsdatadetector follow:
extension string { var nsstring: nsstring { return self nsstring } var length: int { return nsstring.length } var nsrange: nsrange { return nsrange(location: 0, length: length) } var detectdates: [date]? { return try? nsdatadetector(types: nstextcheckingresult.checkingtype.date.rawvalue) .matches(in: self, range: nsrange) .flatmap{$0.date} } } extension collection iterator.element == string { var dates: [date] { return flatmap{$0.detectdates}.flatmap{$0} } }
testing:
let datestrings = ["january 3, 1966","jan 3, 1966", "3 jan 1966"] datestring in datestrings { if let datedetected = datestring.detectdates?.first { print(datedetected) // 1966-01-03 14:00:00 +0000 // 1966-01-03 14:00:00 +0000 // 1966-01-03 14:00:00 +0000 } } let datestrings = ["january 3, 1966","jan 3, 1966", "3 jan 1966"] date in datestrings.dates { print(date) // 1966-01-03 14:00:00 +0000 // 1966-01-03 14:00:00 +0000 // 1966-01-03 14:00:00 +0000 }
Comments
Post a Comment