大家都知道Qt中有QDateTime等有关时间与日期的类,类中包含很多成员函数,可以很方便的实现有关时间与日期的操作,比如:想要获得系统当前的时间与日期,可以调用currentDateTime(); 但是Qt并没有提供设置系统时间的方法,这样我们只能自己来区分平台,调用平台相关的API,这篇文章实现在Windows下的设置。
常用的与时间有关的Win32 API有两个:GetSystemTime(); 与 SetSystemTime(); 下面是函数原型:
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> VOID GetSystemTime(LPSYSTEMTIME lpSystemTime);
BOOL SetSystemTime( const SYSTEMTIME * lpSystemTime );
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 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;
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
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