chandra mohan
chandra mohan

Reputation: 337

What should be the format of a string to convert into NSDate?

I'm getting following two types of strings from server:

  1. 2016-07-28T12:25:31.922247
  2. 2016-07-28T13:39:13

I want to convert them into NSDate. I'm using following snippet to convert but it's failing:

let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss"

I'm not getting the desired output.

Upvotes: 0

Views: 98

Answers (4)

Nirav D
Nirav D

Reputation: 72410

If you doesn't care the fraction of second then you can remove it like this.

var strDate = "2016-07-28T12:25:31.922247"
if strDate.rangeOfString(".") != nil{
     let arr = strDate.characters.split{$0 == " "}.map(String.init)
     strDate = arr[0]
}
//Now you can convert this string to date using same date format
let formatter= NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = formatter.dateFromString(strDate)

Upvotes: 1

jose920405
jose920405

Reputation: 8049

Your date format works in 2016-07-28T13:39:13 but add 'T'

Example: yyyy-MM-dd'T'HH:mm:ss.

But for the 2016-07-28T12:25:31.922247 you need clarifies that this means 922247

the truth had never seen anything like it, but I would try with yyyy-MM-ddTHH:mm:ssZ

Upvotes: 0

David Berry
David Berry

Reputation: 41226

You need to quote the "T" (or any alpha characters that should be present in literal form), try:

let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

Note that this will only parse your second string. To parse your first string you'll need to use:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"

if you care about the fractional seconds. Since NSDateFormatter is a literal parser it doesn't allow you to easily parse either format, if you have to parse both you'll just need to pass it to one, if that fails pass to the other.

Upvotes: 0

AtWork
AtWork

Reputation: 1293

You can get the exact format from this Link

For the second string use this

yyyy-MM-dd'T'HH:mm:ss

Upvotes: 1

Related Questions