Formatting Dates with the formatted() Modifier in SwiftUI

Use SwiftUI 3.0's .formatted() function to format a date.

With SwiftUI 3.0, we can now easily format a date with the .formatted() method. Let's see how easy and simple it is to get different formatted dates with this new method.

Disclaimer

The .formatted() method is only supported in applications running on iOS 15.0 and higher. You'll need Xcode 13 and need to set your Xcode project's iOS target version to iOS 15.0 or higher, or wrap the code presented in this section in an if #available(iOS 15.0, *).

Create a date

First, we'll need a SwiftUI date. You can get today's date by initializing a Date().

let date = Date()

..

Format the date

Next, call the .formatted() method, and you'll automatically get your formatted date!

date.formatted()
// Output: 8/20/2021, 4:27PM

..

You can even pass in arguments inside of the parentheses to format your date however you wish.

date.formatted(.dateTime.day().month().year()) // Output: Aug 20, 2021
date.formatted(.dateTime.day().month()) // Output: Aug 20

date.formatted(.dateTime.month()) // Output: Aug
date.formatted(.dateTime.month(.wide)) // Output: August

date.formatted(.dateTime.weekday())  // Output: Fri
date.formatted(.dateTime.weekday(.wide)) // Output: Friday

date.formatted(.dateTime.day()) // Output: 20

..

Comments