0

The date I'm having is this..

2021-03-05T12:21:18

But I want it in dd-MM-yyyy format. This is what I did for that...

dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss"
let date2 = dateFormatter.date(from: self.Due_Date) //self.Due_Date is 2021-03-05T12:21:18
dateFormatter.dateFormat = "dd-MM-yyyy"                 
self.Due_Date = dateFormatter.string(from: date2!) //CRASH HERE
        

But I get date2 as nil. So the code crashes at self.Due_Date = dateFormatter.string(from: date2!)

What could be the reason for this...?

D.M
  • 510
  • 6
  • 14
  • Not related to your question but `YYYY` is wrong. `Y` is for `YearForWeekOfYear`. What you need is `yyyy` – Leo Dabus Mar 05 '21 at 07:07
  • `print(self.Due_Date)` before parsing it. I guess its value is not `"2021-03-05T12:21:18"` – Leo Dabus Mar 05 '21 at 07:09
  • Actually @LeoDabus its value is `2021-03-05T12:21:18`. Hence I gave the formatter as `"YYYY-MM-dd'T'HH:mm:ss"` in the first line of code. – D.M Mar 05 '21 at 07:15
  • I have seen date strings with a carriage return added. Look closer. – gnasher729 Mar 05 '21 at 08:03

1 Answers1

0

The “yyyy” represents the calendar year of the date while the “YYYY” represents the year of the week.

for detail information, please see this Difference between 'YYYY' and 'yyyy' in NSDateFormatter

let getInputString = "2021-03-05T12:21:18"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        if let getInputDate = dateFormatter.date(from:getInputString){
            dateFormatter.dateFormat = "dd-MM-yyyy"
            let getoutputString = dateFormatter.string(from: getInputDate)
        }  

Note : as per @LeoDabus guidelines please ensure the self.Due_Date is empty or not before start the conversion.

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