Xcode swift am/pm time to 24 hour format

user3772 picture user3772 · Mar 28, 2015 · Viewed 95.9k times · Source

I am trying to convert a am/pm format time to a 24 hour format time

6:35 PM to 18:35

I tried this piece of code on playground but it doesnt seem to work if I put the time alone

let dateAsString = "02/12/15, 6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH"
let date = dateFormatter.dateFromString(dateAsString) //returns nil

Does anyone know how to accomplish this?

Thank you.

Answer

Ian picture Ian · Mar 28, 2015

Just convert it to a date using NSDateFormatter and the "h:mm a" format and convert it back to a string using the "HH:mm" format. Check out this date formatting guide to familiarize yourself with this material.

enter image description here

let dateAsString = "6:35 PM"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.dateFromString(dateAsString)

dateFormatter.dateFormat = "HH:mm"
let date24 = dateFormatter.stringFromDate(date!)