Daniel Oram
Daniel Oram

Reputation: 8411

Converting specific string to NSDate object in swift 2

I have a string representing a date

"2016-06-28T22:26:31.200577Z"

and the dateformatter I use uses the format

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

the extra ".200577" is causing my dateformatter to return nil when I try convert the date string to a NSDate object.

I have tried changing my dateformatter string to

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

but this is not correct. I am unsure whether the ".200577" actually denotes a fraction of a second or is something else like a time zone.. At the moment I can get past this error by splitting the end part off of the string but I do not want to lose this information.

I am looking for help as to what my correct dateformatter string should be.

Upvotes: 0

Views: 351

Answers (2)

ADK
ADK

Reputation: 139

Use the following code to get formatted NSDate object

let dateformatter = NSDateFormatter()
 dateformatter.dateStyle = NSDateFormatterStyle.MediumStyle
 dateformatter.timeStyle = NSDateFormatterStyle.NoStyle
 dateformatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"
 print(dateformatter.dateFromString("2016-06-28T22:26:31.200577Z"))

// Optional(2016-06-28 22:26:31 +0000)

Upvotes: 1

Amit Singh
Amit Singh

Reputation: 2698

You can follow the Unicode Markup Language its

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

Reference : SO Question

Upvotes: 3

Related Questions