asheyla asheyla - 7 months ago 36
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
  • 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)
    
Comments