Convert string with unknown format (any format) to date
我有包含日期字符串的数据。
通常情况下,它会在'Jan。 1966年第3版的字型格式,但由于国际上的差异,不一定总是那样。
我需要读取数据并将其转换为标准日期字符串('YYYY-MM-DD')。
基本上这是我到目前为止所拥有的:
1 2 3 4 | var dataString = 'Jan. 3, 1966' var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = # I DON'T KNOW THE EXACT INPUT FORMAT ! let dateValue = dateFormatter.dateFromString(dataString) |
Xcode 9? Swift 4或Xcode 8.3.2吗? 斯威夫特3.1
您可以按以下方式使用NSDataDetector:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | extension String { var nsString: NSString { return self as 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 where Iterator.Element == String { var dates: [Date] { return flatMap{$0.detectDates}.flatMap{$0} } } |
测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | let dateStrings = ["January 3, 1966","Jan 3, 1966","3 Jan 1966"] for 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"] for 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 } |
经过Swift 4,XCode 9测试
1 2 3 4 5 6 7 | extension String { var detectDate: Date? { let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue) let matches = detector?.matches(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) return matches?.first?.date } } |
测试: