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
相关产品推荐
相关产品推荐

