我使用以下代码将字符串转换为日期:
// Input is "06-10-18, 01:30 pm"
func convertStringToDate(string: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy, hh:mm a"
return formatter.date(from: string)!
}
这在模拟器和我的设备上运行良好,但在几个客户端设备上返回时会崩溃。
我尝试通过让它返回日期字符串来查看问题所在,并且在客户端设备上它返回以下内容:
"06-10-18, 13:30"
为什么它在少数设备上的返回结果不同?
最佳答案
返回的日期是否正确,您可以使用 .timeIntervalSince1970
属性进行检查。发生的情况是,当您打印日期(实际上只是一个 TimeInterval,又名 Double,一个特定时间点,独立于任何日历或时区)时,它会打印其 description属性,以及当前设备设置。
要使用当前区域设置打印日期,请使用 this实例方法:
let date = convertStringToDate(string: "06-10-18, 01:30 pm")
print(date.description(with: Locale(identifier: "en_US_POSIX")))
关于swift - DateFormatter 在特定设备上返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52676392/