Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 823
Pallavi Konda Avatar asked Nov 25 '25 17:11

Pallavi Konda


1 Answers

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)
like image 112
x4h1d Avatar answered Nov 28 '25 07:11

x4h1d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!