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);//转换成UTC时间,以系统设置时区为参考
}
由上可以看出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;
}