Reputation: 1670
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
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
Reputation: 1842
NSDateFormatter
will return an optional NSDate
because maybe it won't be able to parse your input.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