Search code examples
swiftdateformatter

Swift String value converted into strange Date value


extension Date {
    func toString() -> String {
        let dateFormatter = DateFormatter()
        
        dateFormatter.dateFormat = "MMMM dd, Y (E)"
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
        
        return dateFormatter.string(from: self)
    }
}

extension String {
    func toDate() -> Date {
        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "MMMM dd, Y (E)"
        dateFormatter.timeZone = TimeZone(identifier: "UTC")

        return dateFormatter.date(from: self)!
    }
}

That is my code. I want to convert my string value into a right date value. The results i’m getting are totally different form what i want.

Here is an example:

String : September 09, 2021 (Thu)
Converted Date : 2020-12-24 00:00:00 +0000

I want it to be like this:

Converted Date : September 09, 2021 (Thu) (or 2021-09-09 00:00:00 +0000)

Solution

  • Can you change

    dateFormatter.dateFormat = "MMMM dd, Y (E)"
    

    To:

    dateFormatter.dateFormat = "MMMM dd, yyyy (E)"
    

    You pass the full year in String: September 09, 2021 (Thu) so you need to get yyyy to the right way.

    extension String {
        func toDate() -> Date {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MMMM dd, yyyy (E)"
            dateFormatter.timeZone = TimeZone(identifier: "UTC")
            return dateFormatter.date(from: self)!
        }
    }
    

    enter image description here