用Delphi獲取當前系統時間

2021-05-24 14:12:49 字數 1699 閱讀 3390

在開發應用程式時往往需要獲取當前系統時間。儘管y2k似乎已經平安過去,但在我們新開發的應用程式中還是要謹慎處理「時間」問題。

在《融會貫通--delphi4.0實戰技巧》(以下簡稱「該書」)第89頁專門介紹了兩種獲取當前系統時間的方法,但這兩種方法都存在不足或錯誤,以下就此進行討論。

該書第一種方法是利用time()函式獲得當前系統時間,返回結果是tdatetime結構型別的變數。例如:

procedure tform1.button2click(sender: tobject);

vardatetime:tdatetime;

begin

datetime:=time();

caption:=datetostr(datetime)+' '+timetostr(datetime);

end;

但不論何日期,其結果卻都是99-12-30 xx:xx:xx, 顯然日期出錯了。通過分析delphi的幫助,time()用於返回正確的「時間--時分秒」即timetostr(datetime),而不應該用於返回「日期」。事實上,單獨用於返回日期的系統函式是date。

那麼有什麼是既可返回正確的「時分秒」又可返回正確的「年月日」呢? 可以用now函式,例如:

procedure tform1.button1click(sender: tobject);

varmytime: tdatetime;

begin

mytime:=now;

caption:=datetostr(mytime)+' '+timetostr(mytime);

//或直接用 caption := datetimetostr(now);

end;

用now返回的日期格式中年只有2位,即2023年顯示為00, 這似乎不太令人滿意. 此外now和time都只能獲得精確到秒的時間,為了得到更精確的毫秒級時間,可以使用api函式getsystemtime,它對應的tsystemtime型別的定義為:

tsystemtime = record

wyear: word;

wmonth: word;

wdayofweek: word;

wday: word;

whour: word;

wminute: word;

wsecond: word;

wmilliseconds: word;

end;

顯然,在程式邏輯中還能夠方便地使用其結構成?時---各類時間值,因此使用函式getsystemtime具有很大優越性。但該書中該函式的用法是錯誤的,通過查閱windows sdk幫助可知,該函式原型為:

void getsystemtime(lpsystemtime lpst),引數指標lpst獲取系統時間,因此可如以下程式段實現:

procedure tform1.button3click(sender: tobject);

varsystime: tsystemtime;

begin

getsystemtime(systime);

caption:=inttostr(systime.wyear)+' '+inttostr(systime.wmonth);

//if systime.wyear>2000 then

// ......在程式邏輯中利用獲取的各類時間值

end;

綜合以上討論,獲取當前系統時間利用函式getsystemtime比較方便而且靈活。

用Delphi獲取當前系統時間

在開發應用程式時往往需要獲取當前系統時間。儘管y2k似乎已經平安過去,但在我們新開發的應用程式中還是要謹慎處理 時間 問題。在 融會貫通 delphi4.0實戰技巧 以下簡稱 該書 第89頁專門介紹了兩種獲取當前系統時間的方法,但這兩種方法都存在不足或錯誤,以下就此進行討論。該書第一種方法是利用ti...

C C 獲取當前系統時間

方案 優點 僅使用c標準庫 缺點 只能精確到秒級 include include int main void size t strftime char strdest,size t maxsize,const char format,const struct tm timeptr 根據格式字串生成字...

js獲取當前系統時間

var mydate new date mydate.getyear 獲取當前年份 2位 mydate.getfullyear 獲取完整的年份 4位,1970 mydate.getmonth 獲取當前月份 0 11,0代表1月 mydate.getdate 獲取當前日 1 31 mydate.get...