WagnerMatosUK WagnerMatosUK - 1 year ago 78
Swift Question

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:

my function expects
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?

Answer Source

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


See also: Date Format Patterns

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download