relative(presentation:unitsStyle:)
Returns a style for formatting a date as relative to the current date.
Declaration
static func relative(presentation: Date.RelativeFormatStyle.Presentation, unitsStyle: Date.RelativeFormatStyle.UnitsStyle = .wide) -> SelfParameters
- 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(presentation:unitsStyle:) 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"
}