components(style:fields:)
Returns a style for formatting a date interval in terms of specific date components.
Declaration
static func components(style: Date.ComponentsFormatStyle.Style, fields: Set<Date.ComponentsFormatStyle.Field>? = nil) -> SelfParameters
- style:
The style to use for the fields, such as Abbreviated or Narrow.
- fields:
A set of date component fields to include in the formatted output.
Return Value
A date format style that uses the specified style and fields.
Discussion
Use this type method when the call point allows the use of Date.ComponentsFormatStyle. You typically do this when calling the formatted(_:) method of a Range<Date>.
The following example creates a 120-day date range, and then uses a Date.ComponentsFormatStyle to express this as a count of weeks and days:
let date = Date()
let futureDate = Calendar.current.date(byAdding: .day, value: 120, to: date)!
let interval = (date..<futureDate)
let formatted = interval.formatted(
.components(style: .wide,
fields: [.week, .day])) // 17 weeks, 1 day