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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With