You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI Date.FormatStyle无法适配非公历日历的问题排查

SwiftUI Date.FormatStyle无法切换日历格式的解决方案

问题重现

尝试使用SwiftUI的Date.FormatStyle分别展示伊斯兰乌姆古拉日历和系统默认公历,但运行后两个文本均显示系统默认公历。已知DateFormatter手动指定格式可正常适配日历,但希望保留Date.FormatStyle兼顾地区用户偏好的优势。使用Xcode 15.4(注:原提问标注26.4应为笔误)。

复现代码:

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()
    }
}

问题原因

直接修改Date.FormatStyle的calendar属性无法生效——Date.FormatStyle是值类型,且系统用户偏好设置会覆盖该属性的直接赋值,导致指定的日历规则未被应用。

解决方案

使用链式调用的.calendar()修饰符指定目标日历,确保样式强制应用指定的日历规则,同时保留Date.FormatStyle适配地区偏好的特性。

修改后的代码:

import SwiftUI

struct ContentView: View {
    let date = Date()

    var islamicStyle: Date.FormatStyle {
        Date.FormatStyle(date: .numeric, time: .omitted)
            .calendar(Calendar(identifier: .islamicUmmAlQura))
    }

    var body: some View {
        VStack {
            Text(date, format: islamicStyle)
            Text(date, format: .dateTime.year().month().day())
        }
        .padding()
    }
}

也可以直接在.dateTime链式调用中添加日历指定,写法更简洁:

Text(date, format: .dateTime.year().month().day().calendar(Calendar(identifier: .islamicUmmAlQura)))

补充说明

  • 若需同时指定地区格式,可额外添加.locale()修饰符,例如适配沙特阿拉伯地区的伊斯兰日历格式:
    .locale(Locale(identifier: "ar_SA"))
    
  • 该方式既保留了Date.FormatStyle自动适配地区日期格式的优势,又强制应用了指定的日历规则。

内容的提问来源于stack exchange,提问作者Grimxn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 14:18:11