Search code examples
iosswiftnsdateformatter

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:

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?


Solution

  • Your dateFormat for Apr 25 2018 12:00AM is not right. You are using M dd yyyy h:mm A, but format would be 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!)