I'm trying to get SwiftUI to format dates in two different calendars using Date.FormatStyle, but I can't get it to work. What am I missing? Here's a minimal example:

import SwiftUI struct ContentView: View { let date = Date() var islamicStyle: Date.FormatStyle { var style = Date.FormatStyle(date: .numeric, time: .omitted) style.calendar = Calendar(identifier: .islamicUmmAlQura) return style } var body: some View { VStack { Text(date, format: islamicStyle) Text(date, format: .dateTime.year().month().day()) } .padding() } }

Both outputs are in Gregorian (my system calendar) - what am I doing wrong? Xcode 26.4.

p.s. I know I could use a DateFormatter and manually specify a fixed date format (that does respect the calendar), but the benefit of Date.FormatStyle is that it also respects other user preferences like locale.

Grimxn's user avatar

SwiftUI Text formatting seems to overwrite the calendar in the date format with whatever calendar is in the SwiftUI environment. So instead of setting Date.FormatStyle.calendar, set the SwiftUI environment calendar like this:

Text(date, format: Date.FormatStyle(date: .numeric, time: .omitted)) .environment(\.calendar, Calendar(identifier: .islamicUmmAlQura))

Of course, you should still set Date.FormatStyle.calendar if you want to use the format outside SwiftUI.

Sweeper's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.