Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no inverse function for gmtime in libc?

Tags:

posix

time

libc

In libc there are two functions to convert from system time to calendar time - gmtime and localtime, but only localtime has inverse function - mktime. Why there is no inverse function for gmtime, and if there shouldn't be any, why gmtime exists?

like image 904
Igor Liferenko Avatar asked Jul 11 '16 02:07

Igor Liferenko


1 Answers

I've found this piece of code work satisfactorily:

namespace std {
    time_t timegm(tm* _Tm) 
    {
        auto t = mktime(_Tm);
        return t + (mktime(localtime(&t)) - mktime(gmtime(&t)));
    }
}

which satifies the test:

auto t1 = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
auto t2 = std::timegm(std::gmtime(&t1));
EXPECT_EQ(t1, t2);
like image 167
Robert Avatar answered Sep 22 '22 23:09

Robert