Lobuno
Lobuno

Reputation: 1405

First [Monday] of the month, Second [Thursday] of the month, etc. Delphi

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?

Upvotes: 8

Views: 3458

Answers (2)

David Heffernan
David Heffernan

Reputation: 612924

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;

Upvotes: 13

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

This can be done using simple math.

Get the DayOfTheWeek and divide the DayOf by seven.

Upvotes: 4

Related Questions