2004. április 1., csütörtök

Getting the dates of the first and last day of the month of a given date


Problem/Question/Abstract:

How can I get the dates of the first and last day of the month of a given date?

Answer:

FDOM and LDOM

FDOM returns the date that corresponds to the first day of the same month as the date passed as parameter, while LDOM returns the date that corresponds to the last day of the month (subtracting 1 from the date that corresponds to the first day of the next month).

function FDOM(Date: TDateTime): TDateTime;
var
  Year, Month, Day: Word;
begin
  DecodeDate(Date, Year, Month, Day);
  Result := EncodeDate(Year, Month, 1);
end;

function LDOM(Date: TDateTime): TDateTime;
var
  Year, Month, Day: Word;
begin
  DecodeDate(Date, Year, Month, Day);
  if Month < 12 then
    inc(Month)
  else
  begin
    Month := 1;
    inc(Year)
  end;
  Result := EncodeDate(Year, Month, 1) - 1;
end;

Sample call

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(DateToStr(FDOM(Now)));
  ShowMessage(DateToStr(LDOM(Now)));
end;

Copyright (c) 2001 Ernesto De Spirito
Visit: http://www.latiumsoftware.com/delphi-newsletter.php

Nincsenek megjegyzések:

Megjegyzés küldése