本文主要是介绍Delphi 11.3中从一个日期时间中算出当月(当年、当季)的第一天与最后一天,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
函数代码
function DateMonthStart(const DT: TDateTime): TDateTime;
var
Day, Month, Year: Word;
begin
SysUtils.DecodeDate(DT, Year, Month, Day);
Result := SysUtils.EncodeDate(Year, Month, 1);
end;
function DateMonthEnd(const DT: TDateTime): TDateTime;
var
Day, Month, Year: Word;
LastDay: Byte;
begin
SysUtils.DecodeDate(DT, Year, Month, Day);
LastDay := DaysInMonth(DT);
Result := SysUtils.EncodeDate(Year, Month, LastDay);
end;
function DateQuarterStart(const D: TDateTime): TDateTime;
var
Year, Month, Day, Quarter: Word;
begin
SysUtils.DecodeDate(D, Year, Month, Day);
Quarter := 4 - ((12 - Month) div 3);
Month := 0;
SysUtils.IncAMonth(Year, Month, Day, (Quarter * 3) - 2);
Result := SysUtils.EncodeDate(Year, Month, 1);
end;
function DateQuarterEnd(const D: TDateTime): TDateTime;
var
Year, Month, Day, Quarter: Word;
begin
SysUtils.DecodeDate(D, Year, Month, Day);
Quarter := 4 - ((12 - Month) div 3);
// get 1st day of following quarter
Month := 0;
SysUtils.IncAMonth(Year, Month, Day, Quarter * 3 + 1);
// required date is day before 1st day of following quarter
Result := SysUtils.EncodeDate(Year, Month, 1) - 1.0;
end;
function DateYearStart(const DT: TDateTime): TDateTime;
var
Year, Month, Day: Word;
begin
SysUtils.DecodeDate(DT, Year, Month, Day);
Result := SysUtils.EncodeDate(Year, 1, 1);
end;
function DateYearEnd(const DT: TDateTime): TDateTime;
var
Year, Month, Day: Word;
begin
SysUtils.DecodeDate(DT, Year, Month, Day);
Result := SysUtils.EncodeDate(Year, 12, 31);
end;
测试
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(DateTimeToStr(DateMonthStart(Now))) ;
Memo1.Lines.Add(DateTimeToStr(DateMonthEnd(Now))) ;
Memo1.Lines.Add(DateTimeToStr(DateQuarterStart(Now))) ;
Memo1.Lines.Add(DateTimeToStr(DateQuarterEnd(Now))) ;
Memo1.Lines.Add(DateTimeToStr(DateYearStart(Now))) ;
Memo1.Lines.Add(DateTimeToStr(DateYearEnd(Now))) ;
end;
···
这篇关于Delphi 11.3中从一个日期时间中算出当月(当年、当季)的第一天与最后一天的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!