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

Swift NSDateFormatter返回异常年份0005而非2023问题求助

问题分析与解决

这个问题是日本设备特有的**和历纪年(令和、平成等)**导致的:当DateFormatter使用日本地区locale时,系统默认会优先采用和历而非公元纪年,若你的format参数用了yy/y这类短年份格式,就会输出和历的年份(比如令和5年就会显示为0005)。

具体修复方案

  • 强制使用公历:给DateFormatter明确设置公历日历,避免自动切换到和历
    dateFormatter.calendar = Calendar(identifier: .gregorian)
    
  • 检查日期格式字符串:务必使用yyyy(4位公元年份)而非yy/y,避免短年份解析偏差
  • 固定locale(可选):如果不需要适配日本本地纪年场景,可直接指定通用locale,比如:
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    

修正后的代码示例

let timeStamp = Date().timeIntervalSince1970
let date = Date(timeIntervalSince1970: timeStamp)
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale.current
dateFormatter.calendar = Calendar(identifier: .gregorian) // 强制使用公历
dateFormatter.dateFormat = format // 确保format为yyyy-MM-dd这类标准格式
let result = dateFormatter.string(from: date)
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:37:06