Week numbers in Swift
To do week number calculations in Swift, you need to configure a Calendar instance.
var calendar = Calendar(identifier: .gregorian)
calendar.firstWeekday = 2
calendar.minimumDaysInFirstWeek = 4
How to get the week number from a date
To get the ISO week number (1-53), use
calendar.component(.weekOfYear, from: date).
To get the corresponding four-digit year (e.g. 2023), use
calendar.component(.yearForWeekOfYear, from: date).
date is a Date instance.
Read more about component()
in the Swift documentation.