Author: Tomas Rutkauskas
How to count the number of Mondays between two given dates
Answer:
Solve 1:
1 function NumMondays(dt1, dt2: TDateTime): integer;
2 var3 Date1, Date2, DateSpan: integer;
4 Weekday1, DaysInStub: integer;
5 MondayInStub: Boolean;
6 begin7 {Make sure date 1 is smaller than date 2}8 Date1 := MinIntValue([Trunc(dt1), Trunc(dt2)]);
9 Date2 := MaxIntValue([Trunc(dt1), Trunc(dt2)]);
10 {First approximation: complete weeks}11 DateSpan := Date2 - Date1 + 1;
12 result := DateSpan div 7;
13 {Now check if there's a Monday in the stub}14 MondayInStub := false;
15 DaysInStub := DateSpan mod 7;
16 Weekday1 := DayOfWeek(Date1);
17 case Weekday1 of18 {Sunday}19 1: MondayInStub := DaysInStub > 0;
20 {Monday}21 2: MondayInStub := true; {Starts and ends with Monday}22 {Sunday}23 3..7: MondayInStub := (Weekday1 + DaysInStub > 9 {2+7});
24 end;
25 if MondayInStub then26 inc(result);
27 end;
Solve 2:
Something like this should do the trick. I included the variable setup and display
of results from my little test so that it will be obvious what I did.
28 procedure TForm1.Button1Click(Sender: TObject);
29 var30 cnt: integer;
31 StartDate, EndDate: TDate;
32 begin33 cnt := 0;
34 StartDate := StrToDate('4/21/2003');
35 EndDate := StrToDate('5/30/2003');
36 {Actual Monday counting}37 repeat38 if DayOfWeek(StartDate) = 2 then{2 = Monday (Sun = 1 .. Sat = 7) }39 inc(cnt);
40 StartDate := StartDate + 1;
41 until42 StartDate = EndDate;
43 label1.Caption := IntToStr(cnt);
44 end;