转换具有未知格式(任何格式)的字符串到目前为止

时间:2015-09-15 21:07:32

标签: ios swift nsdate nsdateformatter

我的数据包含日期字符串。

通常会出现在Jan。 1966年3月#39;类型格式,但由于国际差异,它可能并不总是那样。

我需要读取数据并将其转换为标准日期字符串(' 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)  

2 个答案:

答案 0 :(得分:23)

Xcode 9•Swift 4 Xcode 8.3.2•Swift 3.1

您可以使用NSDataDetector,如下所示:

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}
    }
}

测试:

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
}

答案 1 :(得分:0)

在Swift 4,xcode 9中进行了测试

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
        }
    }

测试:

print("2018-11-04T23:59:00+00:00".detectDate ?? "") // 2018-11-04 10:00:00 +0000

print("2018/11/4".detectDate ?? "") // 2018-11-04 10:00:00 +0000