我想根据用户偏好设置中的“ 24小时”选项从DateFormatter获取12h或24h格式的时间。
如果我将“ 24-Hour-Time” =“ on”和DateFormatter设置为:
let formatter = DateFormatter()
let locale = Locale(identifier: "en_US")
print(locale) // "en_US (fixed)\n"
formatter.locale = locale
formatter.dateStyle = .none
formatter.timeStyle = .short
formatter.string(from: Date()) // "2:54 PM" (not "14:54")
但是如果我设置:
let locale = Locale.current // "en_US (current)\n"
代替
let locale = Locale(identifier: "en_US") // "en_US (fixed)\n"
结果将是
formatter.string(from: Date()) // "14:54"
如何创建12或24小时格式的自定义语言环境设置。
答案 0 :(得分:-1)
// MARK:-使用它可以将24小时格式转换为12小时格式字符串
func TwelveHourFormateFrom24Hours(time : String)->String
{
let Time = time.components(separatedBy: ".")
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"
if let inDate = dateFormatter.date(from: Time[0])
{
dateFormatter.dateFormat = "h:mm a"
dateFormatter.timeZone = TimeZone.current
let outTime = dateFormatter.string(from: inDate)
print("in \(time)")
print("out \(outTime)")
return outTime
}
return time
}
// MARK:-24小时格式化字符串
func TwentyFourHourFormate(time : String)->String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm a"
if let inDate = dateFormatter.date(from: time)
{
dateFormatter.dateFormat = "H:mm:ss.sss"
let outTime = dateFormatter.string(from: inDate)
print("in \(time)")
print("out \(outTime)")
return outTime
}
return time
}