Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a date string from Rails into Swift

Please bear with me as I'm new to Swift: I'm writing a little app that calls an API (Rails) which return some data. The problem I'm having is that the date provided by the API comes like this: yyyy-MM-dd'T'HH:mm:sssZ my function expects yyyy-MM-dd'T'HH:mm:ssZ Please note the extra second

Here's my function:

public func dateFromString(date: String, format: String) -> NSDate {

    if dateFormatter == nil {
        dateFormatter = NSDateFormatter()
    }

    dateFormatter!.dateFormat = format
    return dateFormatter!.dateFromString(date)!
}

On the console, when I try to run the app I get this:

date String "2015-04-13T12:48:23.310Z"

format String "yyyy-MM-dd'T'HH:mm:ssZ"

Any ideas on how I should resolve this?

like image 380
WagnerMatosUK Avatar asked Dec 14 '22 15:12

WagnerMatosUK


1 Answers

You can do if you use the SSS as format string, like below.

"yyyy-MM-dd'T'HH:mm:ss.SSSZ"

See also: Date Format Patterns

like image 116
kishikawa katsumi Avatar answered Dec 29 '22 18:12

kishikawa katsumi