【问题标题】:Get year's Japanese name from Calendar从日历中获取年份的日文名称
【发布时间】:2020-10-06 12:04:39
【问题描述】:

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

现在我有这个代码:

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

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

【问题讨论】:

  • component(.year, from: Date()) 返回一个Int,得到像“2”这样的值是正常的。使用DateForamtterDates 获取String

标签: swift calendar


【解决方案1】:

那是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())

但是你会得到一个人类难以理解的数字236,所以你应该坚持使用DateFormatter

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 2015-09-14
    • 2010-12-11
    • 1970-01-01
    • 2013-12-05
    • 1970-01-01
    • 2018-04-29
    • 2020-06-17
    相关资源
    最近更新 更多