Contents

localizedString(from:)

Formats a relative time represented by the specified date components.

Declaration

func localizedString(from dateComponents: DateComponents) -> String

Parameters

  • dateComponents:

    The date components to format.

Return Value

A string that represents the formatted relative time from date components.

Discussion

The formatter interprets a negative component value as a date in the past.

let components = DateComponents(day: -2)
let formatter = RelativeDateTimeFormatter()
print(formatter.localizedString(from: components))
// Outputs:  2 days ago

This method formats the value of the least granular unit in the NSDateComponents object, and doesn’t provide a compound format of the date component.

See Also

Converting Dates to Formatted Strings