I like to calculate the difference of local time (in some timezone) and GMT in terms of number of seconds. I use the following code snippet:
time_t now = time(0); // GMT
time_t gmnow = mktime(gmtime(&now)); // further convert to GMT presuming now in local
time_t diff = gmnow - now;
But, I am getting a wrong difference. What I am doing here is querying the current time as GMT through time(0). Then presuming that is a local time, I call gmtime to add the GMT difference factor and re-convert to local time using mktime. This should have shown the difference of GMT and my timezone, but it is showing a extra difference of 1 hour (daylight savings).
For example, my current time is Thu Mar 13 04:54:45 EDT 2014 When I get current time as GMT, that should be: Thu Mar 13 08:55:34 GMT 2014 Considering this is current time, if I call gmtime, this should further proceed, and re-converting back should give me a difference of 4 hr, but I am getting a difference of 5hr.
Is gmtime usage wrong here? Also, how do I know current time zone as well as time in daylight savings?
Got it!
The following code snippet would solve this:
time_t now = time(0); // UTC
time_t diff;
struct tm *ptmgm = gmtime(&now); // further convert to GMT presuming now in local
time_t gmnow = mktime(ptmgm);
diff = gmnow - now;
if (ptmgm->tm_isdst > 0) {
diff = diff - 60 * 60;
}
The trick is to check tm_isdst flag, if applicable and if set, adjust one hour more to diff This works. Thanks to all for your time.