Convert NSString to NSDate in swift
I am trying to convert @ "4:30 PM" (string) to NSDate format. I canβt do this and I quit unexpectedly.
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)
+3
source to share
2 answers
To remove an option, define the constant date
as:
let date = dateFormatter.dateFromString(strDate) as NSDate!
To calculate time in your local timezone add
dateFormatter.timeZone = NSTimeZone(name:"UTC")
In short, this 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)
+3
source to share
-
NSDateFormatter
will return optionalNSDate
, because it might not be able to parse your input. -
NSDateFormatter
also returns an objectNSDate
that only stores the raw date (so it is in GMT timezone), but printing will localize the output. For example, in France I am in GMT + 1 timezone, so the output will always be one hour more than I entered into strDate.
+2
source to share