Skip to content

Type MethodFoundationEssentials

relative(presentation:unitsStyle:)

iOS 15.0+ iPadOS 15.0+ Mac Catalyst 15.0+ macOS 12.0+ tvOS 15.0+ watchOS 8.0+
Returns a style for formatting a date as relative to the current date.
static func relative(presentation: Date.RelativeFormatStyle.Presentation, unitsStyle: Date.RelativeFormatStyle.UnitsStyle = .wide) -> Self

Parameters

presentation

The style to use when describing a relative date; for example, “1 day ago” or “yesterday”.

unitsStyle

The style to use when formatting the quantity or the name of the unit; for example, “1 day ago” or “one day ago”.

Return Value

A relative date format style customized with the specified presentation and unit styles.

Discussion

Use this static method when the call point allows the use of Date.RelativeFormatStyle. You typically do this when calling the formatted(_:) method of Date.

The following example shows the relative format style with two different presentations.

if let past = Calendar.current.date(byAdding: .day, value: -7, to: Date()) {
    let formattedNumeric = past.formatted(
        .relative(presentation: .numeric)) // "1 week ago"
    let formattedNamed = past.formatted(
        .relative(presentation: .named)) // "last week"
}