0

Xcode 9.0.1 · Swift 4 · iPhone 5s

To recreate the problem I'm getting in my app, I've created a single view application and added the following three lines of code to ViewController.viewDidLoad():

    let formatter = DateFormatter()
    formatter.dateFormat = "HH:mm"
    print(formatter.string(from: Date()))

The app is then run on my iPhone and I get the following results:

If the phone is set to 24 hour time (Settings > Date & Time > 24 Hour Time) the code prints "07:45" in the console.

If 24 hour time is switched off at the settings then "7:45 am" is printed in the console.

Question: How do I make the output consistent with the formatter rather than the phone settings?

Vince O'Sullivan
  • 2,611
  • 32
  • 45

2 Answers2

2

DateFormatter uses the system's locale by default, but you can set it yourself to override the default. You can set the locale of the formatter like this:

let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.locale = Locale(identifier: "en_US_POSIX") // This uses am/pm, use a different locale for 24-hour
print(formatter.string(from: Date())) // Prints "12:23"

You can force the time formatting like this:

let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.setLocalizedDateFormatFromTemplate("HH:mm")
print(formatter.string(from: Date())) // Prints "09:47"

formatter.setLocalizedDateFormatFromTemplate("hh:mm")
print(formatter.string(from: Date())) // Prints "9:47 AM"
Marcel
  • 6,393
  • 1
  • 30
  • 44
  • That appears to work. Even though the "en_US" locale favours the 12 hour format, putting it in appears to make the formatter work as expected. (Consequently, the comment appears to be wrong.) I assume any locale might make the formatter work. Some experimentation needed. Thanks. – Vince O'Sullivan Oct 26 '17 at 07:15
  • I see that setting the locale to any value, valid, invalid or even to an empty String appears to fix the problem. – Vince O'Sullivan Oct 26 '17 at 07:26
  • @VinceO'Sullivan you should use the system locale `"en_US_POSIX"` (English (United States, Computer)) when setting a custom dateFormat not `"en_US"` or anything else. – Leo Dabus Oct 26 '17 at 07:38
  • I added the use of `setLocalizedDateFormatFromTemplate` to my answer, I think thats the way to go. – Marcel Oct 26 '17 at 07:53
-1

Change the dateFormat to HH:mm aa:

let formatter = DateFormatter()
formatter.dateFormat = "HH:mm aa"
print(formatter.string(from: Date()))

Output: (24-hour format is on/off)

11:14 AM

Imad Ali
  • 3,261
  • 1
  • 25
  • 33
  • Thanks, but I don't want that format. I want "HH:mm" as per my question. – Vince O'Sullivan Oct 26 '17 at 07:20
  • @VinceO'Sullivan You'll get the same time-format, Except that you'll get the AM/PM in the time. You asked about consistency, this is the one irrespective of the 24-hour format is ON/OFF. Why downvote? – Imad Ali Oct 26 '17 at 07:22