Last active
July 16, 2019 00:31
-
-
Save wenchy/c36e9e3df1f0a016c01000894b6ab3a9 to your computer and use it in GitHub Desktop.
Get timezone offset with cache optimization.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <time.h> | |
#include <iostream> | |
#include <limits> | |
int TimeZoneOffsetSecond() | |
{ | |
// cache, need compute only once | |
static int offset = std::numeric_limits<int>::min(); | |
if (offset != std::numeric_limits<int>::min()) | |
{ | |
return offset; | |
} | |
time_t t = time(NULL); | |
struct tm utc; | |
gmtime_r(&t, &utc); | |
offset = t - mktime(&utc); | |
return offset; | |
} | |
int main() | |
{ | |
// test case 1: 32400 | |
// TZ=:/usr/share/zoneinfo/Asia/Tokyo ./a.out | |
// test case 2: 28800 | |
// TZ=:/usr/share/zoneinfo/Asia/Shanghai ./a.out | |
// test case 3: 10800 | |
// TZ=:/usr/share/zoneinfo/Africa/Kampala ./a.out | |
// test case 4: -18000 | |
// TZ=:/usr/share/zoneinfo/America/Indiana/Indianapolis ./a.out | |
std::cout << TimeZoneOffsetSecond() << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment