FrozenHeart
FrozenHeart

Reputation: 20746

How to constuct NSDate object from String with milliseconds

I need to construct NSDate object from String, so I wrote the following code:

func getNSDateObjectFromString(string: String) -> NSDate { 
    var formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    let date = formatter.dateFromString(string)
    return date!
}

Unfortunately, the input string sometimes may contain milliseconds too. What can I do in this case? I don't find any way to read milliseconds (not in the day) according to the http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

Thanks in advance.

Upvotes: 0

Views: 992

Answers (4)

Roj
Roj

Reputation: 369

A Swift 3 Solution

After a bit of trial and error with the date format this is what worked for me with Swift 3.

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
let date = formatter.date(from: "2017-03-11 13:16:31.177")!
debugPrint(dateFormatter.string(from: date))

and after a round trip results in the expected debug output of

"2017-03-11 13:16:31.177"

Note that using the format "yyyy-MM-dd'T'HH:mm:ss.SSS" resulted in formatter.date(from: returning a nil optional Date.

Upvotes: 1

rintaro
rintaro

Reputation: 51911

As far as I know, the format doesn't support "optional" fields. So you have to try the formats one by one:

func getNSDateObjectFromString(string: String) -> NSDate {
    var formatter = NSDateFormatter()
    formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    var date = formatter.dateFromString(string)

    if date == nil {
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
        date = formatter.dateFromString(string)
    }

    return date!
}

Upvotes: 3

wolffan
wolffan

Reputation: 1104

Are they important? In DateFormatter you create your matching string in years, months, days, hours, mins, secs, but you don't need to. If your matching string does not contain any of them, formatter will just ignore them.

Upvotes: 0

Y.Bonafons
Y.Bonafons

Reputation: 2349

You can try something like:

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"

Upvotes: 1

Related Questions