Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode Swift am/pm time to 24 hour format

I am trying to convert an 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 doesn't 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?

like image 246
user3772 Avatar asked Mar 28 '15 20:03

user3772


People also ask

How to get time in 24 hour format in Swift?

iso8601) // this format to 24 hour let dateFormatter = DateFormatter() dateFormatter. dateFormat = "HH:mm:ss" let twentyFourHour = dateFormatter. string(from: afternoonHour) print(twentyFourHour) // with the new Date.

How to format time in Swift?

dateFormat = "yyyy-MM-dd'T'HH:mm:ss. SSSZ" Needed to manipulate date with timezones and using this worked like a charm to get formatter. string to formatter.

What is 24 hour format datetime?

The pattern dd/MM/yyyy hh:mm:ss aa is used for the 12 hour format and the pattern MM-dd-yyyy HH:mm:ss is used for the 24 hour format.


1 Answers

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" dateFormatter.locale = Locale(identifier: "en_US_POSIX") // fixes nil if device time in 24 hour format let date = dateFormatter.dateFromString(dateAsString)  dateFormatter.dateFormat = "HH:mm" let date24 = dateFormatter.stringFromDate(date!) 
like image 109
Ian Avatar answered Mar 19 '23 18:03

Ian