Vive Vive - 9 months ago 36
iOS Question

Invalid date after conversion 12h -> 24h

I want to convert AM/PM time to 24h. That should be totally trivial... however I'm standing against a weird issue:

let inputDateString = "11:05:45PM"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ssa"
let inputDate = dateFormatter.dateFromString(inputDateString) // "Jan 1, 2000, 12:05 PM" ???

if let inputDate = inputDate {
dateFormatter.dateFormat = "HH:mm:ss"

  1. I thought that maybe it's converting the time using some weird timezone. So I've tried to add
    or GB locale, that didn't help.

  2. Then I've came up with the idea, that maybe it can't set date previous to 01.01.2000 12:00:00 (what is without sense, because it should work at least from year ~1970). So I've added the day, month etc to move it to 2005 year, but the issue still persists.

You can easily paste this to the Playground with
import Foundation
to test it out.

Why am I getting wrong hour?

-- Edit --

If you change
to any other hour like
, the
would be the same :/ But if you change minutes or seconds, it gets updated accordingly.


You need to change the dateFormat to "hh:mm:ssa", as the lowercase h signalizes that the input time is in 12-hour format.

DateFormatter uses the Unicode standard for formatting, so it uses the values found in the Unicode Documentation (Valid for macOS 10.9 and iOS 7 and newer, as of 08/2016).

An easier-to-use reference can be found on