swiftnsdatensdateformatter

Convert string to date in Swift


How can I convert this string "2016-04-14T10:44:00+0000" into an NSDate and keep only the year, month, day, hour?

The T in the middle of it really throws off what I am used to when working with dates.


Solution


  • Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 10.12:

    let isoDate = "2016-04-14T10:44:00+0000"
    
    let dateFormatter = ISO8601DateFormatter()
    let date = dateFormatter.date(from:isoDate)!