Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert date (without knowing the kind) to string

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?

like image 414
Jessica Avatar asked Nov 10 '22 05:11

Jessica


1 Answers

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

like image 127
zaph Avatar answered Nov 14 '22 22:11

zaph