Ron Tabachnik
Ron Tabachnik

Reputation: 5

Convert string to Date() with dateFormatter

I'm trying to convert from string date ("Apr 19, 2020") and between today's date format (Date() just the format) this is the code that I used to convert.

/// Create String
                    let string = (dict["Birthday"] as? String)!
                    // Create Date Formatter
                    let dateFormatter = DateFormatter()
                    // Origin date "Apr 19, 2020"
                    dateFormatter.dateFormat = "MMM d, YYYY"
                    // Convert String to Date format 2020-04-19
                    print(dateFormatter.date(from: string))

but when I run it I get totally different date.. 2021-04-29 22:20:53.888471+0300 is there someone that can help me with this? P.S how to remove the unnecessary parts and to leave just the date? Thank you!

Upvotes: 1

Views: 163

Answers (1)

hoseinali alborzi
hoseinali alborzi

Reputation: 455

let dateFormatter = DateFormatter()

// Origin date "Apr 19, 2020"
dateFormatter.dateFormat = "MMM d, YYYY"

// Convert String to Date format 2020-04-19
let date = dateFormatter.date(from: string)
dateFormatter.dateFormat = "yyyy-MM-dd"

let newDate = dateFormatter.string(from: date!)
print(newDate)

100% ok checked

Upvotes: 1

Related Questions