format a date in to the format month day, year in swift

You can format a date in Swift using DateFormatter class. Below is an example code that formats the current date into "month day, year" format:

main.swift
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy"
let currentDate = Date()
let dateString = dateFormatter.string(from: currentDate)
print(dateString) // Output: May 18, 2021
203 chars
6 lines

In the above code, we first create an instance of DateFormatter with a desired output format. The format string MMMM dd, yyyy specifies that the month should be spelled out (e.g. "May"), followed by the day with a leading zero (e.g. "05" for May 5th), and then the four-digit year.

Next, we get the current date using the Date() initializer, and then call the string(from:) method of the formatter to convert the date into a string. Finally, we print the formatted date string.

gistlibby LogSnag