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
  • .@Anbu.karthik `"MMM dd, yyyy 'at' hh:mm a"` won't be the format always. It could be `am` or `pm` –  Jun 01 '18 at 10:48
  • But @Anbu.karthik isn't `"MMMM dd, yyyy 'at' hh:mm a"` always for A.M ? In my case it could be either AM or PM –  Jun 01 '18 at 11:00
  • @bwv - based on the time format it will change AM or PM , its the 12 hour dateformat – Anbu.Karthik Jun 01 '18 at 11:05
  • .@Anbu.karthik In the answer that you gave, should we not give an if condition to check for the date format..? because the date that I'll get in `order_date ` can be either in the formats `"MMMM dd, yyyy 'at' hh:mm a"` or `"yyyy-MM-dd HH:mm:ss"` –  Jun 01 '18 at 11:18
  • @bwv - check the updated answer – Anbu.Karthik Jun 01 '18 at 11:22
  • Ok @Anbu.karthik Thanks.. –  Jun 01 '18 at 11:36
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