今天有要求想返回一个月有多少天,在网上找了找,用以下的函数可以实现.
Code
1function DaysInAMonth(const AYear,AMonth:Word):Word; //for Delphi5
2 begin
3 Result:=MonthDays[(AMonth=2) and IsLeapYear(AYear),AMonth];
4 end;
5
6procedure TForm1.Button1Click(Sender: TObject);
7var
8 ss:Word;
9 yy,mm,dd:Word;
10begin
11 DecodeDate(Now,yy,mm,dd);
12 ss:=DaysInAMonth(yy,mm);
13 ShowMessage(IntToStr(ss));
14
15end;
比较可以学习和借鉴的地方是MonthDays 和IsLeapYear函数的实现:
MonthDays
1{ The MonthDays array can be used to quickly find the number of
2 days in a month: MonthDays[IsLeapYear(Y), M] }
3
4const
5 MonthDays: array [Boolean] of TDayTable =
6 ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
7 (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
判断是否为润年:
IsLeapYear
1function IsLeapYear(Year: Word): Boolean;
2begin
3 Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
4end;
闰年的计算方法:公元纪年的年数可以被四整除,即为闰年;被100整除而不能被400整除为平年;
被100整除也可被400整除的为闰年。如2000年是闰年,而1900年不是。
判断是星期几:
DayOfWeek
1function DayOfWeek(const DateTime: TDateTime): Word;
2begin
3 Result := DateTimeToTimeStamp(DateTime).Date mod 7 + 1;
4end;
TimeStamp
1{ Date and time record }
2
3 TTimeStamp = record
4 Time: Integer; { Number of milliseconds since midnight }
5 Date: Integer; { One plus number of days since 1/1/0001 }
6 end;