DatePicker is storing different date than displayed in the picker

It seems that there is an time zone issue which I cannot solve by myself.
I have a DatePicker, which shows in the UI another date (+1 day) than the date which is saved to the variable.
The simulator is set to region “Germany” and I live in Germany …

   HStack {
                            VStack (alignment: .leading){
                                DatePicker("Birthday", selection: $user.birthDay, in:, displayedComponents: .date)
                            Toggle("", isOn: $user.birthdayIncluded)
                        .onChange(of: user.birthDay) {

This prints the content of the variable:
2024-02-29 23:18:00 +0000

But it displays in the UI:

How can I synchronize the date shown in the UI and the date stored in the variable?

In that instance I would assume that the date you picked from the Picker was in fact March 1st. The stored date is in UTC time so if you compare the time in Germany to that of London GMT (UTC) then it should be the same time relative to your timezone.

1 Like

Thanks Chris for your quick reply. I really appreciate it.
Based on your assumption (date is stored in UTC) I did more research (thanks google).

Good thing: I found a solution.

First things first:


does show the UTC time (which would result in the day before as seen in the Picker/the UI)


print(user.birthday.formatted(date: .complete, time: .complete))

does show the local time (date as seen in the Picker/ the UI)

Thus, using a better formatted date string in the print statement was the first learning.

But now to the “real” issue.
I was using the date in user.birthday in a vCard, which only accepts the date in very specific formats. One of them is


(Year Month Day in yyyyMMdd)

Initially, I converted the user.birthday with the .iso8601 format:

 let birthdayFormatted = user.birthDay.formatted(.iso8601

which outputs the birthday in the required format, but again -1 day.

As I couldn’t change the timezone in that style, I switched to a DateFormatter:

 let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyyMMdd"
            let birthdayFormatted = dateFormatter.string(from: user.birthDay)

And that is the solution! Now the date from the Picker is correctly formatted :slight_smile:

Well done. You get the super sleuth award for figuring out that.

1 Like