我能够获得当前时间,现在我想用文字输出它。
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")
Run Code Online (Sandbox Code Playgroud)
输出
10:30
如何得到这个 -
现在是十点半了
正如@MwcsMac 在他的回答中指出的那样,解决这个问题的关键是Formatter(曾经被称为NSFormatter),特别是通过将 设置.numberStyle为.spellOut。
虽然这将选择当前的语言环境(以及语言),但问题是许多其他语言而不是英语不使用相同的“半过去”、“四分之一到”术语——例如,在德语中 10:30 是“halb elf”,字面意思是“半(到)十一岁”。
编写假定语言环境为英语/美国的代码是非常糟糕的做法,如果在这些区域之外提供应用程序,可能会被拒绝,因此最好的做法是将“10:30”格式化为“十点三十分”, “zehn dreißig”。
向@MwcsMac 致歉的代码:
import Foundation
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minute = calendar.component(.minute, from: date)
func spell(_ number: Int, _ localeID: String) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
// Specify the locale or you will inherit the current default locale
formatter.locale = Locale(identifier: localeID)
if let s = formatter.string(from: NSNumber(value: number)) {
// AVOID forced unwrapping at all times!
return s
} else {
return "<Invalid>" // or make return optional and return `nil`
}
}
spell(hour, "EN") + " " + spell(minute, "EN") // "nineteen thirty-three"
spell(hour, "FR") + " " + spell(minute, "FR") // ""dix-neuf trente-trois"
spell(hour, "AR") + " " + spell(minute, "AR") // "???? ??? ????? ? ??????"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
466 次 |
| 最近记录: |