Skip to content

Instantly share code, notes, and snippets.

@wenchy
Last active July 16, 2019 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wenchy/c36e9e3df1f0a016c01000894b6ab3a9 to your computer and use it in GitHub Desktop.
Save wenchy/c36e9e3df1f0a016c01000894b6ab3a9 to your computer and use it in GitHub Desktop.
Get timezone offset with cache optimization.
#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