I have two dates:
Monday 26/12/2022 Sunday 01/01/2023
Take this code:
CString strDate = L"2022-12-26 00:00:00";
COleDateTime datMeeting;
datMeeting.ParseDateTime(strDate);
const auto iPublicTalkWeekNumber = _ttoi(datMeeting.Format(L"%W"));
The value of iPublicTalkWeekNumber
is 52.
Now use:
CString strDate = L"2023-01-01 00:00:00";
COleDateTime datMeeting;
datMeeting.ParseDateTime(strDate);
const auto iPublicTalkWeekNumber = _ttoi(datMeeting.Format(L"%W"));
The value of iPublicTalkWeekNumber
is 0.
Why? The 1st Jan 2023 is a Sunday, which rolls back to the 26th Dec, 2022. Why is it not returning 52?
As a result this is messing the logic of my software. The documents say the %W
returns a value 0 - 53, based on the first Monday being week one.
How do I correctly handle this?
This workaround resolves my issue:
COleDateTime datFirstMonday;
COleDateTimeSpan spanDay;
spanDay.SetDateTimeSpan(1, 0, 0, 0);
// Rewind the start / end dates back until we get to the Monday
datFirstMonday = datMeeting;
while (datFirstMonday.GetDayOfWeek() != 2)
datFirstMonday -= spanDay;
const auto iPublicTalkWeekNumber = _ttoi(datFirstMonday.Format(L"%W"));
The above code is used with the Sunday date (but for users of the software it might be another day). Eitherway, we roll back to the associated Monday for that week. Then, we do the test for week number.
This way, I find the matching week number.