format a date in to the format 'yyyy-mm-dd' in swift

To format a date in Swift to the format "yyyy-mm-dd", you can use a DateFormatter. Here's an example:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = Date()
let formattedDate = dateFormatter.string(from: date)
print(formattedDate) // Output: "2022-01-01"
192 chars
6 lines

In this example, we first create a new instance of DateFormatter().

Then, we set the dateFormat property of the dateFormatter instance to the string "yyyy-MM-dd". The uppercase 'M' denotes months, and the lowercase 'm' denotes minutes. The '-' characters are inserted as literals.

Next, we create a Date instance, which represents the current date and time.

Finally, we use the dateFormatter instance to format the date instance as a string in the desired format, using the string(from:) method. The resulting string is stored in the formattedDate constant and printed to the console.

gistlibby LogSnag