【发布时间】:2021-01-07 12:01:30
【问题描述】:
我的用例要求我根据用户在“日期和时间”设置中的 12 小时/24 小时偏好显示不同格式的字符串。
确切地说,我的字符串需要忽略分钟部分,并在 12 小时制时包含“AM/PM”后缀,而在 24 小时制时正好相反。
我最近知道如何使用“jj”模板来实现这一点。 More on this(感谢@larme)
这是我的方法:
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("jj:mm") // As of current time in my locale, this'll display "17:01"
df.locale = .current
if df.string(from: passedDate).count > 5 {
// User has 12-hour time setting i.e: The string has AM/PM suffix
df.setLocalizedDateFormatFromTemplate("jj") // Setting this will ignore the minutes and provide me with the hour and the AM/PM suffix i.e: "5 PM" according to current time
}
现在,这解决了我的问题,但我想知道是否有更清洁的方法来完成这项工作。
【问题讨论】:
-
举个例子说明你想如何显示时间。
标签: ios swift nsdateformatter dateformatter