When developing applications, it is often necessary to obtain the current system time. Even though Y2K seems to have passed safely, we still need to be careful about the "timing" issue in our newly developed applications.
Page 89 of "Integration - Delphi 4.0 Practical Skills" (hereinafter referred to as "the book") specifically introduces two methods of obtaining the current system time, but both methods have shortcomings or errors, which will be discussed below.
The first method in this book is to use the Time() function to obtain the current system time, and the return result is a variable of the TDateTime structure type. For example:
PRocedure TForm1.Button2Click(Sender: TObject);
var
DateTime:TDateTime;
begin
DateTime:=Time();
Caption:=DateToStr(DateTime)+' '+TimeToStr(DateTime);
end;
But no matter what the date is, the result is 99-12-30 xx:xx:xx. Obviously the date is wrong. By analyzing the help of Delphi, Time() is used to return the correct "time - hours, minutes and seconds", that is, TimeToStr (DateTime), and should not be used to return "date". In fact, the only system function used to return dates is Date.
So what can return the correct "hour, minute, second" and the correct "year, month, day"? You can use the Now function, for example:
procedure TForm1.Button1Click(Sender: TObject);
var
mytime: TDateTime;
begin
mytime:=Now;
Caption:=DateToStr(mytime)+' '+TimeToStr(mytime);
//Or use Caption directly := DateTimeToStr(Now);
end;
The date format returned by Now only has 2 digits for the year, that is, the year 2000 is displayed as 00, which seems unsatisfactory. In addition, Now and Time can only obtain time accurate to seconds. In order to obtain a more accurate millisecond-level time, You can use the API function GetSystemTime, and its corresponding TSystemTime type is defined as:
TSystemTime = record
wYear: Word;
wMonth: Word;
wDayOfWeek: Word;
wDay: Word;
wHour: Word;
wMinute: Word;
wSecond: Word;
wMilliseconds: Word;
end;
Obviously, its structure can also be conveniently used in program logic to form time --- various time values, so using the function GetSystemTime has great advantages. However, the usage of this function in the book is wrong. By consulting the Windows SDK help, we can see that the prototype of this function is:
VOID GetSystemTime(LPSYSTEMTIME lpst), the parameter pointer lpst gets the system time, so it can be implemented as the following program segment:
procedure TForm1.Button3Click(Sender: TObject);
var
SysTime: TsystemTime;
begin
GetSystemTime(SysTime);
Caption:=IntToStr(SysTime.wYear)+' '+IntToStr(SysTime.wMonth);
//if SysTime.wYear>2000 then
//...Use the various time values obtained in the program logic
end;
Based on the above discussion, it is more convenient and flexible to obtain the current system time using the function GetSystemTime.