Pallavi Konda
Pallavi Konda

Reputation: 1670

Conversion of NSString to NSDate in swift

I am trying to convert @"4:30 PM" (string) to NSDate format. I am unable to do this and I am getting unexpected out put.

My code

var strDate = "4:30 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.dateFromString(strDate)
print(date)

OutPut : Optional(2000-01-01 11:00:00 +0000)

Upvotes: 3

Views: 721

Answers (2)

x4h1d
x4h1d

Reputation: 6092

To remove optional, define your date constant as:

let date = dateFormatter.dateFromString(strDate) as NSDate!

To calculate time in your local time zone, add

dateFormatter.timeZone = NSTimeZone(name:"UTC")

In summary, here is what you want:

var strDate = "4:30 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = NSTimeZone(name:"UTC")
let date = dateFormatter.dateFromString(strDate) as NSDate!
print(date)

Upvotes: 3

Fantattitude
Fantattitude

Reputation: 1842

  1. NSDateFormatter will return an optional NSDate because maybe it won't be able to parse your input.
  2. NSDateFormatter will also return an NSDate object which only store a raw date (so it's in GMT timezone), but printing it will localize the output. For example in France I am in GMT+1 timezone so the output will always be one hour more than what I entered in strDate.

Upvotes: 2

Related Questions