time_t tm systemtime 互相转换

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;

}

http://blog.csdn.net/c395565746c/article/details/6621153

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值