ARTICLE AD BOX
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.
22.6k11 gold badges74 silver badges89 bronze badges
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.
295k23 gold badges267 silver badges444 bronze badges
Explore related questions
See similar questions with these tags.
