头文件:time.h
函数原型:time_t time(time_t * timer)
功 能: 获取当前的系统时间,返回的结果是一个time_t类型(即int64类型),其实就是一个大整数,其值表示从CUT(Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。
可以通过调用localtime将time_t所表示的CUT时间转换为本地时间(我们是+8区,比CUT多8个小时)并转成struct tm类型,该类型的各数据成员分别表示年月日时分秒。
struct tm的结构为:
struct tm {
int tm_sec; /* seconds after the minute - [0,61] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years since 1900 */
int tm_wday; /* days since Sunday - [0,6] */
int tm_yday; /* days since January 1 - [0,365] */
int tm_isdst; /* daylight savings time flag */
};
在Win32中有SYSTEMTIME类数据结构。
SYSTEMTIME结构定义如下:
SYSTEMTIME STRUCT{
WORD wYear ; // 年
WORD wMonth ; // 月
WORD wDayOfWeek ; // 星期,0=星期日,1=星期一...
WORD wDay ; // 日
WORD wHour ; // 时
WORD wMinute ; // 分
WORD wSecond ; // 秒
WORD wMilliseconds ; // 毫秒
};
/*
** SYSTEMTIME转time_t
*/
time_t systime_to_timet(const SYSTEMTIME& st)
{
struct tm gm = {st.wSecond, st.wMinute, st.wHour, st.wDay, st.wMonth-1, st.wYear-1900, st.wDayOfWeek, 0, 0};
return mktime(&gm);
}
由上可以看出struct tm结构和struct SYSTEMTIME结构的年和月的取值范围是不一样的:
tm.tm_mon = systemtime.wMonth - 1
tm.tm_year = systemtime.wYear - 1900
/*
**time_t转SYSTEMTIME
*/
SYSTEMTIME Time_tToSystemTime(time_t t)
{
tm temptm = *localtime(&t);
SYSTEMTIME st = {1900 + temptm.tm_year,
1 + temptm.tm_mon,
temptm.tm_wday,
temptm.tm_mday,
temptm.tm_hour,
temptm.tm_min,
temptm.tm_sec,
0};
return st;
}
还有一种是通过struct FILETIME作为中间量来转换time_t和systemtime
/*
**time_t转SYSTEMTIME
*/
SYSTEMTIME TimetToSystemTime(time_t t)
{
FILETIME ft;
SYSTEMTIME pst;
LONGLONG nLL = Int32x32To64(t, 10000000) + 116444736000000000;
ft.dwLowDateTime = (DWORD)nLL;
ft.dwHighDateTime = (DWORD)(nLL >> 32);
FileTimeToSystemTime(&ft, &pst);
return pst;
}
/*
**SYSTEMTIME转time_t
*/
time_t SystemTimeToTimet(SYSTEMTIME st)
{
FILETIME ft;
SystemTimeToFileTime( &st, &ft );
LONGLONG nLL;
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
nLL = (ft.dwHighDateTime << 32) + ft.dwLowDateTime;
time_t pt = (long)((LONGLONG)(ui.QuadPart - 116444736000000000) / 10000000);
return pt;
}
GetSystemTime获得的时间是基于通用协调时(UTC, Universal Time Coordinated)
GetLocalTime获得的时间是基于本地时间的