My goal is to precisely calculate the current timezone using C++ standard library, represented as the difference (in seconds) between GMT time and local time.
Example: Italy is GMT+1 so my expected output is -3600
. This offset represents the difference between GMT time (i.e. 12:00) and italian time (i.e. 13:00), ignoring daylight savings.
My actual code looks like this and it seems to work:
long timezone = 0;
bool _tzset() {
std::time_t now = std::time(NULL);
std::time_t local = std::mktime(std::localtime(&now));
std::time_t gmt = std::mktime(std::gmtime(&now));
timezone = static_cast<long> (gmt - local);
return true;
}
From my understanding, what I'm doing here is getting the local time (ignoring DST) and the GMT time (ignoring DST) and just returning the difference.
It looks pretty straightforward but is it correct? Do you see any flaws?
EDIT: I was not clear about my real goal here. I am working on a Win32 framework that has to be ported to the Universal Windows Platform. The problem is that this framework uses a lot of CRT functions that are not supported anymore in the UWP. As you can see, _tzset()
is one of them (also it looks like that the timezone
variable is defined globally in a Win32 environment). In other words what I'm doing here is giving an alternative implementation to these unsupported functions. I can't change the signature of them.