Instance Property


The ISO 8601 week-numbering year.


var yearForWeekOfYear: Int { get set }


The Gregorian calendar defines a week to have 7 days, and a year to have 365 days, or 366 in a leap year. However, neither 365 or 366 divide evenly into a 7-day week, so it is often the case that the last week of a year ends on a day in the next year, and the first week of a year begins in the preceding year. To reconcile this, ISO 8601 defines a week-numbering year, consisting of either 52 or 53 full weeks (364 or 371 days), such that the first week of a year is designated to be the week containing the first Thursday of the year. For a given date, the weekOfYear property indicates which week the date falls in, and yearForWeekOfYear provides the corresponding week-numbering year.

You can use the week-numbering year when specifying a date with NSDateComponents, usually in combination with the weekOfYear. Listing 1 shows this approach. It creates an NSDateComponents instance specifying the first Friday (weekday 6) of the first week of 2016, which started on a Friday. Therefore, this date is January 1, 2016 in the Gregorian calendar. However, on the ISO 8601 calendar, the first week of 2016 begins on the following Monday. This means the first Friday in the first week of 2016 is January 8, 2016 on the ISO 8601 calendar.

Listing 1

Specifying and extracting the yearForWeekOfYear date component in different calendars.

let comps = NSDateComponents()comps.weekday = 6
comps.weekOfYear = 1
comps.yearForWeekOfYear = 2016
let gregorianCalendar = NSCalendar(identifier: .gregorian)!
let gregorianDate = comps as DateComponents)!
let iso8601Calendar = NSCalendar(identifier: .ISO8601)!
let iso8601Date = comps as DateComponents)!

let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.calendar = gregorianCalendar as Calendar
print ("\(formatter.string(from: gregorianDate))") // "Friday, January 1, 2016"
formatter.calendar = iso8601Calendar as Calendar
print ("\(formatter.string(from: iso8601Date))") // "Friday, January 8, 2016"

See Also

Accessing Years and Months

var era: Int

The number of eras.

var year: Int

The number of years.

var quarter: Int

The number of quarters.

var month: Int

The number of months.

var isLeapMonth: Bool

A Boolean value that indicates whether the month is a leap month.