我想在当前语言环境的UILabel中显示当前日期的时间。假设当前时间为15:30(24小时显示)/ 3:30 PM(12小时显示)。现在,如果用户当前的语言环境为12小时显示,则标签应仅显示“ 3:30”,而“ PM”应显示在第二个标签中。我打算使用
someDateTime = Date()
let df = DateFormatter()
df.locale = Locale.autoupdatingCurrent
df.timeStyle = .short
timeLabel.text = df.string(from: someDateTime) // how without AM/PM ?
ampmLabel.text = "???" // how to show only in 12 hours regions?
但是在12小时的区域中,总是附带有AM / PM。我怎样才能轻松地区分这些情况?
答案 0 :(得分:0)
一种解决方案是从日期格式化程序生成时间字符串,然后查看结果字符串是否包含日期格式化程序的amSymbol
或pmSymbol
。如果是这样,请保存该符号并将其从日期字符串中删除。然后,您将拥有所需的两个字符串。
let timeDF = DateFormatter()
timeDF.locale = ... // whatever you need of other than the user's current
timeDF.dateStyle = .none
timeDF.timeStyle = .short
var timeStr = timeDF.string(from: Date())
var ampmStr = ""
if let rng = timeStr.range(of: timeDF.amSymbol) {
ampmStr = timeDF.amSymbol
timeStr.removeSubrange(rng)
} else if let rng = timeStr.range(of: timeDF.pmSymbol) {
ampmStr = timeDF.pmSymbol
timeStr.removeSubrange(rng)
}
timeLabel.text = timeStr.trimmingCharacters(in: .whitespaces)
ampmLabel.text = ampmStr