Skip to content

Instance MethodFoundationEssentials

formatted(date:time:)

iOS 15.0+ iPadOS 15.0+ Mac Catalyst 15.0+ macOS 12.0+ tvOS 15.0+ watchOS 8.0+
Generates a locale-aware string representation of a date using specified date and time format styles.
func formatted(date: Date.FormatStyle.DateStyle, time: Date.FormatStyle.TimeStyle) -> String

Parameters

date

The style for describing the date part.

time

The style for describing the time part.

Return Value

A string, formatted according to the specified date and time styles.

Discussion

When displaying a date to a user, use the convenient formatted(date:time:) instance method to customize the string representation of the date. Set the date and time styles of the date format style separately, according to your particular needs.

For example, to create a string with a full date and no time representation, set the date style to complete and the time style to omitted. Conversely, to create a string representing only the time, set the date style to omitted and the time style to complete.

let birthday = Date()

birthday.formatted(date: .complete, time: .omitted) // Sunday, January 17, 2021
birthday.formatted(date: .omitted, time: .complete) // 4:03:12 PM CST

You can create string representations of a Date instance with several levels of brevity using a variety of preset date and time styles. This example shows date styles of long, abbreviated, and numeric, and time styles of shortened, standard, and complete.

let birthday = Date()

birthday.formatted(date: .long, time: .shortened) // January 17, 2021, 4:03 PM
birthday.formatted(date: .abbreviated, time: .standard) // Jan 17, 2021, 4:03:12 PM
birthday.formatted(date: .numeric, time: .complete) // 1/17/2021, 4:03:12 PM CST

birthday.formatted() // Jan 17, 2021, 4:03 PM

The default date style is abbreviated and the default time style is shortened.

For the default date formatting, use the formatted() method. To customize the formatted measurement string, use the formatted(_:) method and include a Date.FormatStyle.

For more information about formatting dates, see Date.FormatStyle.