format date ios 15 in swift

Starting with iOS 15, you can use the DateFormatter API with the new style property to format dates. Here is how you can format a date based on a specific style:

main.swift
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .none

let formattedDateString = formatter.string(from: date)

print(formattedDateString)
// Output: September 20, 2021
220 chars
10 lines

In the above code, we first create a Date object. Then we create an instance of the DateFormatter. We set the dateStyle property to .long and timeStyle property to .none. Finally, we use the string(from:) method of the DateFormatter to format the date and store the result in the formattedDateString constant.

You can choose the dateStyle and timeStyle properties based on your specific needs. The available options for dateStyle are .none, .short, .medium, and .long and for timeStyle are .none, .short, .medium, and .long.

related categories

gistlibby LogSnag