How to convert date (without knowing the kind) to

2019-04-08 18:23发布

I have an array of NSDate objects that I'm trying to convert to a string. My way of converting them is with NSDateFormat, but, if there's another better way, I'd be happy to hear.

The most things a date would have is:

Days-Hours-Minutes-Seconds-Milliseconds

But some will have less, like:

Minutes-Seconds-Milliseconds

Or even less. Now I will have to convert them to a string. Would I have to create if statements to determine if it has days, hours, and so on, or is there an easier way of doing this?

1条回答
Animai°情兽
2楼-- · 2019-04-08 18:51

Example using NSDataDetector (Swift 2.0):

let textDate = "dan's march 31, 1975 12:34 pm";

do {
    let dd = try NSDataDetector(types: NSTextCheckingType.Date.rawValue)
    if let tcr :NSTextCheckingResult = dd.firstMatchInString(textDate, options:[], range:NSMakeRange(0, textDate.utf16.count)),
       let date = tcr.date {
            print("date: \(date)")
        }
}
catch {
    print("Data Detector error!")
}

Output:

date: 1975-03-31 16:34:00 +0000

查看更多
登录 后发表回答