UTC时间与时区时间转换

描述

时间日期与time stamp转换

参考

  • C语言实现将时间戳转换为年月日时分秒和将年月日时分秒转换为时间戳

代码

  • Date.h
#ifndef __DATE_H__
#define __DATE_H__
/*******************************function********************/
/**function: UTC2Time4
 * description: UTC to time
 */
time_t UTC2Time4(time_t tm_rect, int zone);
/**function: Time2UTC4
 * description: time to UTC
 */
time_t Time2UTC4(time_t tm_rect, int zone);
#endif /* End of #ifndef __DATE_H__ */
  • Date.c
#include
#include

#include "Date.h"

/*********************************** Code ************************************/
/**function: UTC2Time4
 * description: UTC to time
 */
time_t UTC2Time4(time_t tm_rect, int zone)
{
    time_t rect = tm_rect;
    struct tm tblock;
    struct tm *tm_now;
    tm_now = &tblock;
    
    rect = rect + (long)zone * 60 * 60;
    
    if(DAYLIGHT_SAVING_TIME == GetCfgDSTFlag())
    {
        rect = Time2DST2(rect);
    }

    return rect;
}
/**function: Time2UTC4
 * description: time to UTC
 */
time_t Time2UTC4(time_t tm_rect, int zone)
{
    time_t rect = tm_rect;
    struct tm tblock;
    struct tm *tm_now;
    tm_now = &tblock;

    if(DAYLIGHT_SAVING_TIME == GetCfgDSTFlag())
    {
        rect = DST2Time2(rect);
    }
    
    rect = rect - (long)zone * 60 * 60;
    
    return rect;
}
  • 调用
    time_t t;
    t = time(NULL);
    time_t rect;
    int timezone = 8;
    rect = Time2UTC4(t, timezone);
    printf("rect:%lu, t:%lu\n", rect, t);

    struct tm *tblock;
    t = time(NULL);
    tblock = localtime(&t);
    rect = mktime(tblock);
    printf("rect:%lu\n", rect);
    rect = UTC2Time4(rect, timezone);
    printf("rect:%lu\n", rect);

你可能感兴趣的:(UTC时间与时区时间转换)