formatted(_:)
Generates a locale-aware string representation of a date using the specified date format style.
Declaration
func formatted<F>(_ format: F) -> F.FormatOutput where F : FormatStyle, F.FormatInput == DateParameters
- format:
The date format style to apply to the date.
Return Value
A string, formatted according to the specified style.
Discussion
For full customization of the string representation of a date, use the formatted(_:) instance method of Date and provide a Date.FormatStyle object.
You can achieve any customization of date and time representation your app requires by appying a series of convenience modifiers to your format style. This example applies a series of modifiers to the format style to precisely define the formatting of the year, month, day, hour, minute, and timezone components of the resulting string.
// Call the .formatted method on an instance of Date passing in an instance of Date.FormatStyle.
let birthday = Date()
birthday.formatted(
Date.FormatStyle()
.year(.defaultDigits)
.month(.abbreviated)
.day(.twoDigits)
.hour(.defaultDigits(amPM: .abbreviated))
.minute(.twoDigits)
.timeZone(.identifier(.long))
.era(.wide)
.dayOfYear(.defaultDigits)
.weekday(.abbreviated)
.week(.defaultDigits)
)
// Sun, Jan 17, 2021 Anno Domini (week: 4), 11:18 AM America/ChicagoFor the default date formatting, use the formatted() method. For basic customization of the formatted date string, use the formatted(date:time:) and include a date and time style.
For more information about formatting dates, see Date.FormatStyle.