While trying to write code which returns 24 hours less than a given time, mktime()
shows inconsistent output. I calculate it similar to this: current_time(GMT) - 86400
which should return the right value. All we need to do is calculate based on the input time; we used mktime()
to change the time and get the GMT time and then do the regular calculation. I included my code below.
#include <stdio.h>
#include <time.h>
int main()
{
time_t currentTime, tempTime;
struct tm *localTime;
time(¤tTime);
//localTime = localtime(¤tTime);
localTime = gmtime(¤tTime); //get the time in GMT as we are in PDT
printf("Time %2d:%02d\n", (localTime->tm_hour)%24, localTime->tm_min);
localTime->tm_hour = 19; // Set the time to 19:00 GMT
localTime->tm_min = 0;
localTime->tm_sec = 0;
tempTime = mktime(localTime);
//tempTime = mktime(localTime) - timezone;
printf("Current time is %ld and day before time is %ld\n", currentTime, (currentTime - 86400));
printf("Current timezone is %ld \n", timezone);
printf("New time is %ld and day before time is %ld\n",tempTime, (tempTime - 86400));
}
But when we check the output it is coming back incorrect after the call to call mktime()
. Below is the output of above program.
$ ./a.out
Time 11:51
Current time is 1341229916 and day before time is 1341143516
New time is 1341284400 and day before time is 1341198000
$ ./print_gmt 1341229916
Mon Jul 2 11:51:56 2012
$ ./print_gmt 1341143516
Sun Jul 1 11:51:56 2012
$ ./print_gmt 1341284400
Tue Jul 3 03:00:00 2012
$ ./print_gmt 1341198000
Mon Jul 2 03:00:00 2012
$ date
Mon Jul 2 04:52:46 PDT 2012
Now if we un-comment the line which subtracts the timezone (present in time.h), then the output is as expected. Below is the value for timezone in above program
$ ./a.out
. . .
Current timezone is 28800
. . .
So why is there such inconsistent behavior for mktime()
although the man pages do not mention such adjustment of the timezone.
Is there something we are missing while doing such conversions?
Thanks in advance.