在vc中,我们往往需要获取系统时间以做一些处理,我在项目中用到的,和在网上找到的,都贴出来:
A:
1 使用time_t time( time_t * timer ) 精确到秒
计算时间差使用double difftime( time_t timer1, time_t timer0 )
2 使用clock_t clock() 得到的是CPU时间 精确到1/CLOCKS_PER_SEC秒
3 使用DWORD GetTickCount() 得到的是系统运行的时间 精确到毫秒
4 如果使用MFC的CTime类,可以用CTime::GetCurrentTime() 精确到秒
5 要获取高精度时间,可以使用
BOOL QueryPerformanceFrequency(LARGE_INTEGER *lpFrequency)获取系统的计数器的频率
BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount)获取计数器的值
然后用两次计数器的差除以Frequency就得到时间。
6 还有David的文章中提到的方法:
Multimedia Timer Functions
The following functions are used with multimedia timers.
timeBeginPeriod/timeEndPeriod/timeGetDevCaps/timeGetSystemTime
timeGetTime/timeKillEvent/TimeProc/timeSetEvent 精度很高
Q:GetTickCount()函数,说是毫秒记数,是真的吗,还是精确到55毫秒?
A:
GetTickCount()和GetCurrentTime()都只精确到55ms(1个tick就是55ms)。如果要精确到毫秒,应该使用timeGetTime函数或QueryPerformanceCounter函数。具体例子可以参考QA001022 "VC++中使用高精度定时器"、QA001813 "如何在Windows实现准确的定时"和QA004842 "timeGetTime函数延时不准"。
Q:vc++怎样获取系统时间,返回值是什么类型的变量呢?
GetLocalTime,和上面用法一样,返回的是你所在地区的时间,中国返回的是北京时间
LPSYSTEMTIME lpSystemTime // address of system time structure
);
函数就可以获得了,其中LPSYSTEMTIME 是个结构体
含:年,月,日,周几,小时,分,秒,毫秒。
The SYSTEMTIME structure represents a date and time using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
typedef struct _SYSTEMTIME { // st
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;
我用过的:
CString NowTimeToStr()
{
COleDateTime oleDt= COleDateTime::GetCurrentTime();
CString codeuptime = oleDt.Format(" %Y-%m-%d %H:%M:%S");
return codeuptime;
}