使用Delphi,我需要一个函数来评估当前日期,并查看它是否为例如月的第三个星期日等。

用伪代码:

function IsFirst(const CurrentDateTime: TDateTime; const Day: Word): Boolean;
/// Day can be 1-7 (monday to sunday)
begin
  Result:= ??
end;

需要另一个函数来计算该月的第二,第三,第四和最后一天。 DateUtils似乎没有类似的东西。有任何想法吗?

最佳答案

此功能是您需要的:

function IsFirst(const DateTime: TDateTime; const Day: Word): Boolean;
begin
  Result := (DayOfTheWeek(DateTime)=Day) and
    InRange(DayOfTheMonth(DateTime), 1, 7);
end;

第二次出现的等效函数为:
function IsSecond(const DateTime: TDateTime; const Day: Word): Boolean;
begin
  Result := (DayOfTheWeek(DateTime)=Day) and
    InRange(DayOfTheMonth(DateTime), 8, 14);
end;

我确定您可以填写第三,第四和第五的详细信息。您可能更喜欢编写单个通用函数,如下所示:
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;

关于delphi - 该月的第一天[星期一],该月的第二天[星期四],依此类推。Delphi,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8847693/

10-13 02:27