Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 779
Lobuno Avatar asked Jan 13 '12 08:01

Lobuno


2 Answers

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;
like image 115
David Heffernan Avatar answered Oct 11 '22 23:10

David Heffernan


This can be done using simple math.

Get the DayOfTheWeek and divide the DayOf by seven.

like image 38
Jens Mühlenhoff Avatar answered Oct 12 '22 00:10

Jens Mühlenhoff