现在的位置: 首页 > 综合 > 正文

time_t、struct tm和ctime的转换

2013年12月06日 ⁄ 综合 ⁄ 共 866字 ⁄ 字号 评论关闭

1,time_t 转 struct tm

struct tm *localtime( const time_t *timer );

2,struct tm 转 time_t

time_t mktime( struct tm *timeptr );

3,ctime 转 time_t
用ctime类中的gettime成员函数即可

 

//指定time_t类型的时间,格式化为YYYYMMDDHH24MISS型的字符串

void FormatTime(time_t time1, char *szTime)

{

         struct tm tm1;

 

#ifdef WIN32

        tm1 = *localtime(&time1);

#else

        localtime_r(&time1, &tm1 );

#endif

        sprintf( szTime, "%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d",

                     tm1.tm_year+1900, tm1.tm_mon+1, tm1.tm_mday,

                         tm1.tm_hour, tm1.tm_min,tm1.tm_sec);

}

 

//指定YYYYMMDDHH24MISS型的时间,格式化为time_t型的时间

time_t FormatTime2(char * szTime)

{

        struct tm tm1;

        time_t time1;

 

        sscanf(szTime, "%4d%2d%2d%2d%2d%2d",     

                     &tm1.tm_year, 

                     &tm1.tm_mon, 

                     &tm1.tm_mday, 

                     &tm1.tm_hour, 

                     &tm1.tm_min,

                     &tm1.tm_sec);

 

        tm1.tm_year -= 1900;

          tm1.tm_mon --;

 

        tm1.tm_isdst=-1;

 

        time1 = mktime(&tm1);

        return time1;

}

抱歉!评论已关闭.