โญ Support Time.now: Join our Premium Plan for an ad-free experience! โญ Support Us: Go Premium Ad-Free!

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.

Step-by-Step Instructions

  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.

Good to Know

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.