0
if let date:Date = formatter.date(from: dateString) {
    formatter.dateFormat = "dd MMM yyyy hh:mm a
    print("Formatted Date:\(formatter.string(from: date))")
    return formatter.string(from: date)
}

Will the Date Format "dd MMM yyyy hh: mm a" will display time-based on the Device Settings?
I can see the date and time in the correct format as chosen in the Settings (i,e) 24Hr when I turned on a 24Hr switch in the Settings and 12Hr format when I turned off 24Hr switch.

But my app users say, he is unable to see time in 24Hrs even he turned on the 24Hr switch in the settings.
Any suggestions and Inputs are welcome. Thanks

  • 2
    "hh:mm a" this is for 12 hour format. You should use the `.dateStyle` or `.timeStyle` properties for `DateFormatter` if you want to use a format that is controlled by current locale and user settings. – Joakim Danielson Jul 23 '20 at 12:36
  • Formatted Date:Jul 21, 2020 at 8:41:25 PM, but I am specific to show Date and Time in this format in my app "dd MMM yyyy hh:mm" (Date should be first, and milliseconds not required for me) – mubashir meddekar Jul 23 '20 at 15:23
  • See answer below – Joakim Danielson Jul 23 '20 at 16:24

1 Answers1

1

As Joakim said in their comment, the dateFormat property sets a fixed format.

I don't think there is a "semi-fixed" format that lets you specify a non-standard format that nevertheless honors the user's 12/24 hour time display setting.

It will ignore the user's settings. If you want the time format to honor the user's locale and settings, use the properties dateStyle and timeStyle:

lazy var timeFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    return formatter
}()

I did a Google search, and found this (Objective-C) code that lets you tell whether the user has requested 12 hour or 24 hour time:

https://spin.atomicobject.com/2011/05/03/detect-24-hour-user-settings-on-ios-devices/

It wouldn't be that hard to convert that code to Swift. (Ideally, you should also subscribe to the notification the system sends out when the user changes their clock/calendar preferences.)

You could use that to figure out the user's 12/24 hour setting, and adjust your dateFormat accordingly (to either "dd MMM yyyy hh:mm a" or "dd MMM yyyy HH:mm a")

Duncan C
  • 128,072
  • 22
  • 173
  • 272