0

I have a date within order_date in this format May 31, 2018 at 3:35 PM

I’m converting it to Date like so…

if let order_date = value["order_date"] as? String {

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let date = dateFormatter.date(from: order_date)

}

But I'm getting date as nil. What could be the issue..?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253

2 Answers2

0

your dateformat is wrong change your format to

dateFormatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm a"

for e.g if you get the month as Mar then use - MMM, if you get March then use - MMMM

you can check the dateformat's in here

for full answer

 if let order_date = value["order_date"] as? String {

let dateFormatter = DateFormatter()
 dateFormatter.dateFormat = "MMMM dd, yyyy 'at' hh:mm a"
  var date = dateFormatter.date(from: order_date)
    if date == nil{
        dateFormatter.dateFormat =  "yyyy-MM-dd HH:mm:ss"
        date = dateFormatter.date(from: order_date)
    }
 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
 let myStringafd = dateFormatter.string(from: date!)
 print(myStringafd)

}

for detail dateforamt conversion you get here

Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
0

Replace your code with below :

if let order_date = value["order_date"] as? String
    {

        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "MMM dd, yyyy 'at' hh:mm a"

        let date = dateFormatter.date(from: order_date)

    }
Kalpesh Panchasara
  • 1,730
  • 2
  • 15
  • 27