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

使用Japanese Calendar创建日期时年份显示4040的异常问题排查

Swift日本日历日期解析异常原因

核心原因

你使用的.japanese日历采用日本官方年号纪年体系(如令和、平成),而非公历纪年:

  • 当创建DateComponents时未指定era(纪元)参数,日本日历默认使用当前纪元(令和),并将year值解析为当前纪元的年份(而非公历年份)。
  • 令和元年对应公历2019年,因此令和2022年的公历换算为:2019 + 2022 - 1 = 4040,这就是输出中出现4040年的直接原因。

解决方法

方式1:直接使用公历日历解析

如果目标是获取公历2022年的日期,直接用公历日历即可:

let dateComponent = DateComponents(year: 2022, month: 12, day: 30)
print(Calendar(identifier: .gregorian).date(from: dateComponent))
// 输出:Optional(2022-12-29 17:00:00 +0000)(时区差异导致的日期偏移属正常现象)

方式2:指定纪元后使用日本日历

若必须使用日本日历,需明确纪元及对应年号年份(令和4年=公历2022年):

let japaneseCalendar = Calendar(identifier: .japanese)
// 获取令和纪元的标识值
if let reiwaEra = japaneseCalendar.eras.first(where: { $0.name == "令和" }) {
    let components = DateComponents(era: reiwaEra.value, year: 4, month: 12, day: 30)
    print(japaneseCalendar.date(from: components))
}

方式3:从公历日期转日本日历组件

如果已有公历日期,可直接转换为日本日历的纪年组件:

let gregorianDate = Calendar(identifier: .gregorian).date(from: DateComponents(year:2022, month:12, day:30))!
let japaneseComponents = Calendar(identifier: .japanese).dateComponents([.era, .year, .month, .day], from: gregorianDate)
print(japaneseComponents)
// 输出:year:4, month:12, day:30, era:3(对应令和4年)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:55:20