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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With