我正在尝试将此日期"07:05:45 PM“转换为"19:05:45",此代码不起作用,我在其他关于日期、代码的问题中没有找到解决方案:
Import Foundation
let string = "07:05:45 PM"
let dateFormatter = DateFormatter ()
dateFormatter.locale = Locale (identifier: "en_US_POSIX")
dateFormatter.dateFormat = "hh:mm a"
let date = dateFormatter.date (from: string)
print (date)我试过了
dateFormatter.dateFormat = "hh:mm:ss"
dateFormatter.dateFormat = "hh:mm:ss a"
dateFormatter.dateFormat = "hh:mm"我删除了"PM“并尝试:
dateFormatter.dateFormat = "hh:mm"
dateFormatter.dateFormat = "hh:mm:ss" // that code is the only who worked, but doesn't solves the format problem发布于 2017-04-04 00:47:36
您需要使用末尾使用"a“的DateFormatter进行读取,然后不只是使用print(date)打印日期,还需要使用另一个使用24小时时钟格式("HH")且没有AM/PM的DateFormatter。
发布于 2017-04-04 00:54:07
你应该这样做:
let givenString = "07:05:45 PM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm:ss a"
if let date = dateFormatter.date (from: givenString) {
dateFormatter.dateFormat = "HH:mm:ss"
let desiredFormattedString = dateFormatter.string(from: date) // "19:05:45"
}简单地说,您给定的日期格式是"hh:mm:ss a“,而所需的日期格式是"HH:mm:ss”。通过设置适当的格式(使用dateFormatter),desiredFormattedString字符串应包含所需的格式化日期。
请注意,为了获得24小时时钟约定的格式,您应该将小时设置为HH,显然- hh表示12小时时钟约定。
https://stackoverflow.com/questions/43190002
复制相似问题