我有包含日期字符串的数据。
通常它会在 'Jan. 3, 1966' 类型格式,但由于国际差异,可能并不总是如此。
我需要读取数据并将其转换为标准日期字符串('YYYY-MM-DD')。
基本上这是我目前所拥有的:
var dataString = 'Jan. 3, 1966'
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = # I DON'T KNOW THE EXACT INPUT FORMAT !
let dateValue = dateFormatter.dateFromString(dataString)
Best Answer-推荐答案 strong>
Xcode 11.4 • Swift 5.2 或更高版本
您可以按如下方式使用 NSDataDetector:
extension String {
var nsString: NSString { self as NSString }
var length: Int { nsString.length }
var nsRange: NSRange { .init(location: 0, length: length) }
var detectDates: [Date]? {
try? NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)
.matches(in: self, range: nsRange)
.compactMap(\.date)
}
}
extension Collection where Iterator.Element == String {
var dates: [Date] { compactMap(\.detectDates).flatMap{$0}
}
}
测试:
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
}
关于ios - 将未知格式(任何格式)的字符串转换为日期,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/43972217/
|