WeekOfTheMonth returns the week of the month represented by the TDateTime value specified with AValue. The value returned will be 1 through 6.

The first week of a month is defined as the first week with four or more days in that month. So if the first day of the month is a Friday, Saturday, or Sunday, the first one, two, or three days of the month are defined as belonging to the last week of the previous month.

Similarly, if the last day of the month is a Monday, Tuesday, or Wednesday, then the last one, two, or three days of the month are defined as belonging to the first week of the next month.

To count weeks based on the actual calendar weekday of the TDateTime value, use the NthDayOfWeek function instead.

If AValue represents a Saturday that is the first day of a month, WeekOfTheMonth returns 5 (or maybe 4), indicating the last week of the previous month, while NthDayOfWeek returns 1 if AValue is the first Saturday in the month.

WeekOfTheMonth uses the ISO 8601 standard definition of a week, where a week is considered to start on a Monday, and end on a Sunday.

Please also refer to NthDayOfWeek.

Declaration: function WeekOfTheMonth(const AValue: TDateTime): Word;

In this example, the month of October 2023 is used as the test month.

procedure OnMapEvent(var Value:Variant);
var
TheDate : TDateTime;
TheWeek : word;
begin
//1st Oct 23 is a Sunday, so returns 4 (being 4th week of September 23)
TheDate := EncodeDateTime(2023, 10, 01, 14, 25, 15, 650);
TheWeek := WeekOfTheMonth(TheDate);
LogInfo('The week of the month is '+IntToStr(TheWeek));
 
//3rd Oct 23 is a Tuesday, returns 1 (being 1st week of October 23)
TheDate := EncodeDateTime(2023, 10, 03, 14, 25, 15, 650);
TheWeek := WeekOfTheMonth(TheDate);
LogInfo('The week of the month is '+IntToStr(TheWeek));
end;