从日历中获取年份的日文名称

Get year's Japanese name from Calendar

我正在我的应用程序中处理自定义日历。 我注意到在日本日历中,有些年份不是数字(这是苹果日历的截图)

现在我有这个代码:

let year = Calendar(identifier: .japanese).component(.year, from: Date())
print("Current year: \(year)")

但是该代码的结果是 Current year: 2。 我想知道如何将年份作为本地化字符串而不是数字,所以“2 Reiwa”而不是 2。 谢谢

那是era name,就像公历中的AD/BC。

您可以使用G格式说明符来指定它:

let f = DateFormatter()
f.calendar = Calendar(identifier: .japanese)
f.dateFormat = "G y"
f.string(from: Date()) // Reiwa 2

你也可以通过component(_:from:)获得:

Calendar(identifier: .japanese).component(.era, from: Date())

但是你会得到一个相当 human-unreadable 的数字 236,所以你应该坚持使用 DateFormatter