Home > Software design >  Swift - Get weekOfYear for a DateComponents entry
Swift - Get weekOfYear for a DateComponents entry

Time:12-06

I'm facing some problems to get the weekOfYear for a valid DateComponents value. This code

let cal = Calendar.current
let dc = DateComponents(calendar:cal, year: 2023, month: 1, day:12)
let woy = dc.weekOfYear

print("Week of year: \(woy)")

generates

Week of year: nil

as an output.

I've expected 2...

CodePudding user response:

It's because DateСomponents just struct, it contains only values from initializer, should be:

let dc = DateComponents(year: 2023, month: 1, day:12)
let woy = cal.component(.weekOfYear, from: cal.date(from: dc)!)
print(woy)

CodePudding user response:

DateComponents is a simple type. It is merely a collection of date components. It does not do date computations like calculating the week of year. That's the job of Calendar. You did not give it a week of year when you initialise the date components, so you get nil when you ask for it.

You can ask the calendar to make a Date out of the DateComponents you have, and ask it what the week of year is:

let cal = Calendar.current
let dc = DateComponents(calendar:cal, year: 2023, month: 1, day:12)
if let date = cal.date(from: dc) {
    // prints 2 as expected
    print(cal.component(.weekOfYear, from: date))
}
  • Related