How to convert a UTC date & time to a time_t in C++?

前端 未结 4 987
一整个雨季
一整个雨季 2021-01-05 03:26

I want to convert a UTC date & time given in numbers for year, month, day, etc. to a time_t. Some systems offer functions like mkgmtime or timegm

4条回答
  •  太阳男子
    2021-01-05 04:09

    Here is a solution I came up with for myself after not finding anything in the standard library to do this for me. This methods only uses basic arithmetic for it calculations making it much faster than looping over every year between 1970 and the date provided. But as with most of the previous answers, this one depends on time_t being implemented using Unix/Epoch time, and doesn't work for timestamps older than 1970, which is't necessary for me.

    #include 
    #include 
    
    constexpr unsigned int count_leapyears(unsigned int year) {
        assert(year > 0);
        return year / 4 - year / 100 + year / 400;
    }
    
    time_t timeutc(tm utc) {
        assert(utc.tm_year >= 70);
        constexpr unsigned int const leaps_before_epoch = count_leapyears(1970);
        unsigned int leapdays = count_leapyears(utc.tm_year + 1899) - leaps_before_epoch;
        unsigned int unix_time;
    
        unix_time = ((utc.tm_year - 70) * 365 + leapdays) * 86400;
        unix_time += utc.tm_yday * 86400 + utc.tm_hour * 3600 + utc.tm_min * 60 + utc.tm_sec;
    
        return unix_time;
    }
    

提交回复
热议问题