UTC日期转时间戳

时间:2021-09-25 02:33:59

网上的方法用mktime来转换日期到时间戳,会被当前环境的时区影响,现在这么做,用UTC的日期转时间戳这样要转换各地的时区也简单

unsigned long  
utcMktime(const unsigned int year0, const unsigned int mon0,  
       const unsigned int day, const unsigned int hour,  
       const unsigned int min, const unsigned int sec)  
{  
    unsigned int mon = mon0, year = year0;  
    /* 1..12 -> 11,12,1..10 */  
    if (0 >= (int) (mon -= 2)) {  
        mon += 12;  /* Puts Feb last since it has leap day */  
        year -= 1;  
    }  
  
    return ((((unsigned long)  
          (year/4 - year/100 + year/400 + 367*mon/12 + day) +  
          year*365 - 719499  
        )*24 + hour /* now have hours */  
      )*60 + min /* now have minutes */  
    )*60 + sec; /* finally seconds */  
}

使用很简单这样就行了

//UTC时间的2019/4/25 13:24:17即北京时间2019/4/25 21:24:17
printf("---%d---\n",(int)utcMktime(2019,4,25,13,24,17));