Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
126 views
in Technique[技术] by (71.8m points)

ios - Convert string with unknown format (any format) to date

I have data that contains a date string.

Normally it would be in a 'Jan. 3, 1966' type format, but because of international differences, it may not always be exactly that.

I need to read the data in and convert it into a standard date string ('YYYY-MM-DD').

Basically this is what I have so far:

var dataString = 'Jan. 3, 1966'  
var dateFormatter = NSDateFormatter()  
dateFormatter.dateFormat = # I DON'T KNOW THE EXACT INPUT FORMAT !
let dateValue = dateFormatter.dateFromString(dataString)  
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Xcode 11.4 ? Swift 5.2 or later

You can use NSDataDetector as follow:

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

Testing:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...