【发布时间】:2020-08-16 04:09:42
【问题描述】:
这个问题不是第一次被问到,但没有任何解决方案适合我。我从以下格式“14:45”的 Api 响应中获取字符串中的时间。
我想将此时间与当前时间进行比较,为此我需要将此字符串转换为 Time formate(swift sports)
转换后我总是得到nil
我尝试了多种方法,但没有一种方法对我有用,其中一种仅供参考,我不知道我在这里缺少什么
感谢您的回复
func stringToTime(str:String) -> Date{ // 14:45 passed here in str
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
print(str)
//here time string prints
let date = dateFormatter.date(from: (str))
print(date)
//date is nil here, should be 02:45 pm
return date!
}
【问题讨论】:
-
看起来您在格式中指定了上午/下午,但您将其排除在 str 之外