skip to Main Content

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!

2

Answers


  1. Try to set locale explicitly to DatePicker, like

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

    Documentation:

    demo

    Login or Signup to reply.
  2. 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(…))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search