iosswiftdatecalendarnsdatecomponents

Wrong date from components


So this is interesting:

po Calendar.default.date(from: DateComponents(year: 2022, month: 1, hour: 16, minute: 1, second: 1, weekday: 1, weekOfMonth: 1))
▿ Optional<Date>
  ▿ some : 2021-12-26 23:01:01 +0000
    - timeIntervalSinceReferenceDate : 662252461.0

I'm expecting January 1st 2022, but I'm getting December 26th 2021? Why is it doing this? Am I doing something wrong?


Solution

  • It's because the date components you are providing are contradictory. You have weekDay 1 (which will probably be a Sunday or Monday, depending on your locale) but the 1 jan 2022 is a Saturday.

    (you also used Calendar.default when I think you meant Calendar.current?)

    If you take out the weekDay term you will get the correct answer:

    Calendar.current.date(from: DateComponents(year: 2022, month: 1, hour: 16, minute: 1, second: 1, weekOfMonth: 1))
    
    // "Jan 1, 2022 at 4:01 PM"
    

    You could also remove the weekOfMonth term as it is superfluous when you are specifying the actual date.