Soutenez Time.now : Rejoignez notre Plan Premium pour une expérience sans publicité ! Soutenez-nous : Passez Premium sans pub !

Week numbers in Swift

To get the current ISO 8601 week number in Swift, use the following code snippet:

let calendar = Calendar(identifier: .iso8601) let week = calendar.component(.weekOfYear, from: Date())

* Ensure your system or application regional settings are set to follow ISO 8601 standards (weeks start on Monday) if the output varies.

Instructions étape par étape

  1. Create a calendar with the ISO 8601 identifier: Calendar(identifier: .iso8601).
  2. Call calendar.component(.weekOfYear, from: Date()).
  3. For the ISO year use the .yearForWeekOfYear component.

Bon à savoir

Using Calendar.current instead of the .iso8601 identifier makes the result depend on the user's locale settings (some regions start weeks on Sunday). Always pin the identifier for reproducible week numbers.