Count the number of Mondays between two given dates (Views: 29)
Problem/Question/Abstract: How to count the number of Mondays between two given dates Answer: Solve 1: function NumMondays(dt1, dt2: TDateTime): integer; var Date1, Date2, DateSpan: integer; Weekday1, DaysInStub: integer; MondayInStub: Boolean; begin {Make sure date 1 is smaller than date 2} Date1 := MinIntValue([Trunc(dt1), Trunc(dt2)]); Date2 := MaxIntValue([Trunc(dt1), Trunc(dt2)]); {First approximation: complete weeks} DateSpan := Date2 - Date1 + 1; result := DateSpan div 7; {Now check if there's a Monday in the stub} MondayInStub := false; DaysInStub := DateSpan mod 7; Weekday1 := DayOfWeek(Date1); case Weekday1 of {Sunday} 1: MondayInStub := DaysInStub > 0; {Monday} 2: MondayInStub := true; {Starts and ends with Monday} {Sunday} 3..7: MondayInStub := (Weekday1 + DaysInStub > 9 {2+7}); end; if MondayInStub then inc(result); 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. procedure TForm1.Button1Click(Sender: TObject); var cnt: integer; StartDate, EndDate: TDate; begin cnt := 0; StartDate := StrToDate('4/21/2003'); EndDate := StrToDate('5/30/2003'); {Actual Monday counting} repeat if DayOfWeek(StartDate) = 2 then {2 = Monday (Sun = 1 .. Sat = 7) } inc(cnt); StartDate := StartDate + 1; until StartDate = EndDate; label1.Caption := IntToStr(cnt); end; |