Determining the week number when given a TDateTime
I have seen this one asked quite a few times: How do you get the week number of a given date? Pass a TDateTime variable to CalendarWeek() below and it will calculate and return the week number. Thanks to Ralph Friedman for this code. functionCalendarWeek(ADate: TDateTime): integer; { Code adapted from Ralph Friedman (TeamB) <[email protected]> } { Calculates calendar week assuming: - Monday is the 1st day of the week. - The 1st calendar week is the 1st week of the year that contains a Thursday. If result is 53, then previous year is assumed. } var firstOfYear: TDateTime; day, dayOne, month, monthOne, year: word; begin DecodeDate(ADate, year, month, day);
dayOne := 0; caseDayOfWeek(EncodeDate(year, 1, 1)) of 1: dayOne := 2; // Sunday 2: dayOne := 1; // Monday 3: dayOne := 31; // Tuesday 4: dayOne := 30; // Wednesday 5: dayOne := 29; // Thursday 6: dayOne := 4; // Friday 7: dayOne := 3; // Saturday end;
ifdayOne > 4 then begin Dec(year); monthOne := 12 end else monthOne := 1;
firstOfYear := EncodeDate(year, monthOne, dayOne); ifADate < firstOfYear then Result := 53 else Result := (Trunc(ADate - firstOfYear) div 7) + 1; end;