Search code examples
iosswiftnsdateformatter

Date formatter not changing properly


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...?


Solution

  • 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.