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


  • NSDateFormatter

    will return optional NSDate

    , because it might not be able to parse your input.
  • NSDateFormatter

    also returns an object NSDate

    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







All Articles