Last Run on XCODE 11.6 / Swift 5.2 Last Run on XCODE 12.0 beta 4 / Swift 5.3

Definition Link to heading

Calendar - A definition of the relationships between calendar units (such as eras, years, and weekdays) and absolute points in time, providing features for calculation and comparison of dates.

The Calendar is a value type (struct) that provides with functions that can assist us in decoupling the component information from a given date like the year, month, day of week etc.

let date = Date()
print("Date: \(date.description)")

Method - component() Link to heading

We can then use the component instance method provided by Calendar to figure out the year, month, day of the week for a given date.

func component(_ component: Calendar.Component, from date: Date) -> Int

The method takes two arguments, one for the component of interest that we can find out from the Calendar.Component enum and a Date instance. In the code below, we create a calendar instance for the gregorian calendar.

let calendar = Calendar(identifier: .gregorian)

let day = calendar.component(.day, from: date)
print("Day: \(day)")

let weekday = calendar.component(.weekday, from: date)
print("weekday: \(weekday)")

let month = calendar.component(.month, from: date)
print("month: \(month)")

let year = calendar.component(.year, from: date)
print("year: \(year)")

An interesting enum case is of weekdayOrdinal which returns the ordinal position within the month. For example, in the Gregorian calendar a weekday ordinal unit of 2 for a weekday unit 3 indicates “the second Tuesday in the month”.

let weekdayOrdinal = calendar.component(.weekdayOrdinal, from: date)
print("weekdayOrdinal: \(weekdayOrdinal)")

Apart from these, there are numerous more enum cases that you can explore as well at Apple’s documentation for Component.

Method - dateComponents() Link to heading

An alternative method dateComponents returns multiple components for a given date instance. The code snippet below returns multiple components for the specified date.

let yearMonthDay = calendar.dateComponents([.year, .month, .day], from: date)
print("\(yearMonthDay)")