Using Delphi, I need a function to evaluate the current date and see if it's, for example, the Third Sunday of the month, etc.
In pseudocode:
function IsFirst(const CurrentDateTime: TDateTime; const Day: Word): Boolean;
/// Day can be 1-7 (monday to sunday)
begin
Result:= ??
end;
Another function would be needed to calculate the Second, Third, Forth and Last of the month. DateUtils seems to have nothing like that. Any ideas?
This function is what you need:
function IsFirst(const DateTime: TDateTime; const Day: Word): Boolean;
begin
Result := (DayOfTheWeek(DateTime)=Day) and
InRange(DayOfTheMonth(DateTime), 1, 7);
end;
The equivalent function for the second occurrence is:
function IsSecond(const DateTime: TDateTime; const Day: Word): Boolean;
begin
Result := (DayOfTheWeek(DateTime)=Day) and
InRange(DayOfTheMonth(DateTime), 8, 14);
end;
I'm sure you can fill out the details for third, fourth and fifth. You may prefer to write a single general function like this:
function IsNth(const DateTime: TDateTime; const Day: Word;
const N: Integer): Boolean;
var
FirstDayOfWeek, LastDayOfWeek: Integer;
begin
LastDayOfWeek := N*7;
FirstDayOfWeek = LastDayOfWeek-6;
Result := (DayOfTheWeek(DateTime)=Day) and
InRange(DayOfTheMonth(DateTime), FirstDayOfWeek, LastDayOfWeek);
end;
This can be done using simple math.
Get the DayOfTheWeek
and divide the DayOf
by seven.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With