Calendar/DateComponents: Trying to find the first date in a week

Trying to find the fist date in the week of date 2020-04-17 (week 16).

I'm expecting the first day in the week to be 04-13 (a Monday) since I've set the firstWeekday as 2.

But the result date is 2020-04-12, which seems incorrect to me. Can anyone explain if I'm doing something wrong here, or have some incorrect understanding? Thanks very much.

Playground is here:

I believe the computation is correct, but you're confusing the computed date with the output printed to the console. On my computer, the output of the "wrong" print statement is:

Date: 2020-04-12 22:00:00 +0000

Note that a Date value has no time zone information. If you print a Date value to the console, Foundation will always print it in GMT. Since my time zone is 2 hours ahead of GMT, this date (April 12 at 22:00 GMT) is equal to April 13 at 00:00 in my time zone, so the computation is actually correct.

On your computer, the output might be different because your time zone might be different. If you use a fresh DateFormatter (which by default uses the current time zone/calendar) to print the date, you should see the date you expect.

Your assertion in the last line is failing because you're not taking the time zone into account. Your expectedDate value is set to April 13 at 00:00 GMT. This does not correspond to April 13 at 00:00 in any other time zone.

let expectedDate = formatter.date(from: "2020-04-13 00:00:00 +0000")
XCTAssertEqual(firstDayInWeek, expectedDate, "Date did not match expected")
1 Like

Thanks very much for your help, I see it now.

Updated gist as well:

1 Like