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?
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.
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!)
Swift 3
Time format 24 hours to 12 hours
let dateAsString = "13:15"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "h:mm a"
let Date12 = dateFormatter.string(from: date!)
print("12 hour formatted Date:",Date12)
output will be 12 hour formatted Date: 1:15 PM
Time format 12 hours to 24 hours
let dateAsString = "1:15 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
let date = dateFormatter.date(from: dateAsString)
dateFormatter.dateFormat = "HH:mm"
let Date24 = dateFormatter.string(from: date!)
print("24 hour formatted Date:",Date24)
output will be 24 hour formatted Date: 13:15
Swift 3 *
Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-
Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds
func timeConversion24(time12: String) -> String {
let dateAsString = time12
let df = DateFormatter()
df.dateFormat = "hh:mm:ssa"
let date = df.date(from: dateAsString)
df.dateFormat = "HH:mm:ss"
let time24 = df.string(from: date!)
print(time24)
return time24
}
Input
07:05:45PM
Output
19:05:45
Similarly
Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-
Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM
func timeConversion12(time24: String) -> String {
let dateAsString = time24
let df = DateFormatter()
df.dateFormat = "HH:mm:ss"
let date = df.date(from: dateAsString)
df.dateFormat = "hh:mm:ssa"
let time12 = df.string(from: date!)
print(time12)
return time12
}
Input
19:05:45
Output
07:05:45PM