asheyla asheyla - 2 years ago 332
Swift Question

Swift convert string to date

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

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

Kind regards

Answer Source
  • Convert the ISO8601 sting to date

    let isoDate = "2016-04-14T10:44:00+0000"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.dateFromString(isoDate)!
  • Get the date components for year, month, day and hour from the date

    let units : NSCalendarUnit = [.Year, .Month, .Day, .Hour]
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(units, fromDate: date)!
  • Finally create a new NSDate object and strip minutes and seconds

    let finalDate = calendar.dateFromComponents(components)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download