[英]Swift date from string always returns nil
I have a date that is a string that looks like this: 我有一个看起来像这样的字符串的日期:
Apr 25 2018 12:00AM
What I am trying to do is convert this date format to yyyy-MM-dd and then convert it back to a string, I have a tried the following: 我想做的就是将此日期格式转换为yyyy-MM-dd,然后将其转换回字符串,我尝试了以下方法:
let formatter = DateFormatter()
formatter.dateFormat = "M dd yyyy h:mm A"
let SLAIssuedFinalGradingDate = formatter.date(from: tableDic["SLAIssuedFinalGradingDate"] as! String)
formatter.dateFormat = "yyyy-MM-dd"
let SLAIssuedFinalGradingDateString = formatter.string(from: SLAIssuedFinalGradingDate!)
But SLAIssuedFinalGradingDate
always returns nil, what am I doing wrong? 但是SLAIssuedFinalGradingDate
总是返回nil,我在做什么错?
Your dateFormat
for Apr 25 2018 12:00AM
is not right. 您的Apr 25 2018 12:00AM
dateFormat
不正确。 You are using M dd yyyy h:mm A
, but format would be MMM dd yyyy hh:mma
. 您正在使用M dd yyyy h:mm A
,但格式为MMM dd yyyy hh:mma
。
Use this link to check date format . 使用此链接检查日期格式 。
Code Should be: 代码应为:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMM dd yyyy hh:mma"
let SLAIssuedFinalGradingDate = formatter.date(from: tableDic["SLAIssuedFinalGradingDate"] as! String)
formatter.dateFormat = "yyyy-MM-dd"
let SLAIssuedFinalGradingDateString = formatter.string(from: SLAIssuedFinalGradingDate!)
Your dateFormat
string is incorrect. 您的dateFormat
字符串不正确。 A DateFormatter
will always return nil if the dateFormat string does not match the supplied string. 如果dateFormat字符串与提供的字符串不匹配,则DateFormatter
将始终返回nil。
"MMM dd yyyy hh:mma"
This is what you're after. 这就是你所追求的。 I suggest you review a DateFormatter cheat sheet and familiarise yourself with the symbols. 建议您查看DateFormatter 备忘单并熟悉这些符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.