//相关函数: SysUtils.DateTimeToTimeStamp(); SysUtils.TimeStampToDateTime(); SysUtils.TimeStampToMSecs(); SysUtils.MSecsToTimeStamp(); Windows.GetTickCount; Windows.GetCurrentTime; {GetCurrentTime 和 GetTickCount 一样, 是调用了 GetTickCount.}
TDate、TTime 与 TDateTime 的尺寸是一样的, 互相转换也不会损失数据; 存在的意义也只是便于理解.
比较有意思的是 TTimeStamp 结构:
TTimeStamp = record Time: Integer; { "毫秒" 表示的时间, 自: 0:0:0:0 } Date: Integer; { "天" 表示的日期, 自: 1/1/0001 } end;
{TDateTime 与 TTimeStamp 互相转换的例子} var T: TDateTime; TS: TTimeStamp; begin T := EncodeDateTime(2009, 5, 22, 11, 22, 33, 999); TS := DateTimeToTimeStamp(T); ShowMessage(IntToStr(TS.Time)); //40953999; 当日已逝去了 40953999 毫秒 ShowMessage(IntToStr(TS.Date)); //733549; 自 0001-1-1 的第 733549 天 T := TimeStampToDateTime(TS); ShowMessage(FormatDateTime('yyyy-m-d h:m:s:z', T)); //2009-5-22 11:22:33:999 end;
假如我们要想知道自 0001-1 0:0:0:0 到 2009-5-22 11:22:33:999 总的毫秒数, 根据上面的结果不难算出:
733549*24*60*60*1000 + 40953999 = 63378674553999.
不过这有现成的函数: TimeStampToMSecs、MSecsToTimeStamp.
{TimeStampToMSecs、MSecsToTimeStamp 示例:} var T: TDateTime; TS: TTimeStamp; ms: Comp; {这是 TimeStampToMSecs 返回的类型} begin T := EncodeDateTime(2009, 5, 22, 11, 22, 33, 999); TS := DateTimeToTimeStamp(T); ms := TimeStampToMSecs(TS); ShowMessage(FloatToStr(ms)); //63378674553999 TS := MSecsToTimeStamp(ms); T := TimeStampToDateTime(TS); ShowMessage(FormatDateTime('yyyy-m-d h:m:s:z', T)); //2009-5-22 11:22:33:999 end;
另外: GetTickCount 函数可获取从开机时间到当前时间的毫秒数, 结合上面, 可以算出开机时间:
{获取开机时间的例子} var T1: Int64; T2,T3: Comp; T4: TDateTime; begin T1 := GetTickCount; {从开机到现在的毫秒数} T2 := TimeStampToMSecs(DateTimeToTimeStamp(Now)); {从 0001-1-1 到当前时间的毫秒数} T3 := T2 - T1; {从 0001-1-1 到开机时刻的毫秒数} T4 := TimeStampToDateTime(MSecsToTimeStamp(T3)); {从 0001-1-1 到开机时刻的时间} ShowMessage(DateTimeToStr(T4)); {显示开机时间} end;