Home > Mobile >  SwiftUI DatePicker format is different on each device, how to make it always display the same chosen
SwiftUI DatePicker format is different on each device, how to make it always display the same chosen

Time:07-15

SwiftUI DatePicker in my app is displayed in three different formats:

In Xcode Preview:

enter image description here

In Simulator:

enter image description here

On Device:

enter image description here

I wonder, how will the users see it?

I want it to be displayed in the "14 Jul 2022" format, "Jul 14, 2022" is also fine, but I don't like the "7/14/22" format.

Please help me - How can I do it?

EDIT: It's even worse than that (although this happens only on the simulator) - the DatePicker uses different formats in different places in my app!

CodePudding user response:

The SwiftUI DatePicker adheres to the user's locale and date settings. On iPhone, you can change them in the system settings General > Language & Region as well as General > Date & Time. Usually, you should not mess with the format of the DatePicker since if you hard-code a specific format a user from a different region may get confused.

You can override the locale and thus the formatting if you really insist on overriding the user's preference:

DatePicker(…)
    .environment(\.locale, Locale(…))

CodePudding user response:

Try to set locale explicitly to DatePicker, like

DatePicker(
    // ... other things

    displayedComponents: .date
)
.environment(\.locale, Locale(identifier: "us"))  // << here !!

Documentation:

demo

  • Related