我从日期格式化程序中得到了一些非常奇怪的结果:
let testDate = Date(timeIntervalSinceReferenceDate: 725840000.0)
print(testDate)
2024-01-01 22:13:20 +0000
let fmt = DateFormatter()
fmt.timeZone = TimeZone(abbreviation: "America/Los_Angeles")
fmt.dateFormat = "h:mm a"
print(fmt.string(from: testDate))
14:13 //where's the am/pm, as specified?
fmt.dateFormat = "h:mm a z"
print(fmt.string(from: testDate))
14:13 PM PST //14:13 PM is just wrong!
出现几个问题:
h:mm a
是正确的,并且它链接到Apple的文档,所以这是不匹配的在文档和实现之间?当我想获得 12 小时时间时,尽管设备是 24 或 12,但我遇到了同样的问题 这就是我如何实现它的
let fullDate = NSDate(timeIntervalSince1970: 725840000.0)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss" // first u format as 24h time
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // this important
var time = fullDate.description.components(separatedBy: " ")[1]
let time24 = dateFormatter.date(from: time) // get the 24h time
//now convert to 12H time
dateFormatter.dateFormat = "h:mm a"
time = dateFormatter.string(from: time24!)