Qt設置系統時間(使用SetSystemTime API函數)


大家都知道Qt中有QDateTime等有關時間與日期的類,類中包含很多成員函數,可以很方便的實現有關時間與日期的操作,比如:想要獲得系統當前的時間與日期,可以調用currentDateTime(); 但是Qt並沒有提供設置系統時間的方法,這樣我們只能自己來區分平台,調用平台相關的API,這篇文章實現在Windows下的設置。

常用的與時間有關的Win32 API有兩個:GetSystemTime();  與  SetSystemTime();  下面是函數原型:

 

VOID GetSystemTime(LPSYSTEMTIME lpSystemTime);
BOOL SetSystemTime( const SYSTEMTIME *lpSystemTime ); 

 我們查一下 MSDN 看看 LPSYSTEMTIME 與 SYSTEMTIME 是什么東東:

復制代碼
typedef struct _SYSTEMTIME {
    WORD wYear;
    WORD wMonth;
    WORD wDayOfWeek;
    WORD wDay;
    WORD wHour;
    WORD wMinute;
    WORD wSecond;
    WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME; 
復制代碼

 從中我們知道 SYSTEMTIME 為結構體類型,LPSYSTEMTIME為結構體指針,傳遞給兩個函數的參數都必須是指針或引用類型,下面看一個Qt的調用實例:

復制代碼
 1 #include <QtCore/QCoreApplication>
 2 #include <iostream>
 3 #include <time.h>
 4 #include <windows.h>
 5 #include <QDateTime>
 6 #include <QDebug>
 7 using namespace std;
 8 
 9 bool setDate(int,int,int);
10 int main(int argc, char *argv[])
11 {
12     QCoreApplication a(argc, argv);
13     qDebug()<<QDateTime::currentDateTime()<<endl;  // Qt API 輸出當前時間
14    setDate(2011,1,1);                             //設置時間
15     qDebug()<<QDateTime::currentDateTime()<<endl;  // Qt API 獲取當前時間
16    return 0;   //讓程序完成任務直接退出吧...
17 }
18 
19 bool setDate(int year,int mon,int day)
20 {
21     SYSTEMTIME st;     
22     GetSystemTime(&st);    // Win32 API 獲取系統當前時間,並存入結構體st中
23     st.wYear=year;
24     st.wMonth=mon;
25     st.wDay=day;
26 
27    return SetSystemTime(&st);    //Win32 API 設置系統時間
28 }
29 

 

http://www.cnblogs.com/hicjiajia/archive/2010/08/27/1810363.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM