目前我正在使用此代码将时间从 String
转换为 Date
:
public static func dateFromTime(_ time: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "k:mm"
formatter.locale = NSLocale.current
return formatter.date(from: time)!
}
这在我的设备上有效,但在模拟器上崩溃了。据我所知,它们都使用 12 小时格式。
此方法在崩溃时收到的字符串是"5:30 AM"
。
此代码可能在模拟器而非设备上崩溃的任何其他原因?
最佳答案
您的代码因日期格式不正确而崩溃!
对于 ,"5:30 AM"
使用 "h:mm a"
,而不是 "k:mm"
。
为避免任何类型的崩溃,请像下面这样更新您的代码。 .
public static func dateFromTime(_ time: String) -> Date {
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
formatter.locale = NSLocale.current
if let date = formatter.date(from: time)
{
return date
}
print("Invalid arguments ! Returning Current Date . ")
return Date()
}
关于ios - 将时间从字符串转换为日期仅在模拟器上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45393024/