time_t tm systemtime 互相转换

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

 

头文件: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,59] */
        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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值