....
I took the sample code, put a main() around it and did a very quick
successful test.
Here is my code:
....
This code worked on linux. But on Windows with Borland C++Builder 5 tzset()
did not change _timezone and _daylight after putenv(). So the result was off
by 1 hour. Instead of putenv(TZ=\"\"") I had to set both _timezone and
_daylight to 0. Then the results were the expected ones. I did not need to
save the old values of _timezone and _daylight. Calling tzset() restored
them.
Here is my new code (with #ifdef for both linux and C++Builder):
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#ifdef linux
#define _timezone timezone
#define _daylight daylight
#endif
int main(int argc, char *argv[])
{
struct tm sZeit1,
sZeit2,
*pZeit;
time_t lZeit;
char *TZ1,
*TZ2,
buf[80];
if (argc != 3)
printf("%s dd.mm.YYYY hh:mm:ss\n"
"takes the arguments as GMT and prints the local time\n",
argv[0]);
else
{
memset(&sZeit1, 0, sizeof(sZeit1));
if (sscanf(argv[1], "%d.%d.%d",
&sZeit1.tm_mday, &sZeit1.tm_mon, &sZeit1.tm_year) != 3)
printf("%s is not dd.mm.YYYY\n", argv[1]);
else
{
sZeit1.tm_mon --;
sZeit1.tm_year -= 1900;
if (sscanf(argv[2], "%d:%d:%d",
&sZeit1.tm_hour, &sZeit1.tm_min, &sZeit1.tm_sec) != 3)
printf("%s is not hh:mm:ss\n", argv[2]);
else
{
memcpy(&sZeit2, &sZeit1, sizeof(sZeit2));
#ifdef linux
lZeit = timegm(&sZeit2);
printf("timegm(%s %s) = %ld\n", argv[1], argv[2], lZeit);
#endif
TZ1 = getenv("TZ");
if (! TZ1)
puts("TZ = NULL");
else
printf("TZ = %s\n", TZ1);
#ifdef linux
putenv("TZ=");
TZ2 = getenv("TZ");
if (! TZ2)
puts("TZ = NULL");
else
printf("TZ = %s\n", TZ2);
#else
_daylight = 0;
_timezone = 0;
#endif
printf("_daylight = %d\n", _daylight);
printf("_timezone = %d\n", _timezone);
lZeit = mktime(&sZeit2);
printf("GMT mktime(%s %s) = %ld\n", argv[1], argv[2], lZeit);
if (TZ1)
{
strcpy(buf, "TZ=\"");
strncat(buf, TZ1, sizeof(buf) - strlen(buf) - 1);
strncat(buf, "\"", sizeof(buf) - strlen(buf) - 1);
putenv(buf);
}
else
#ifdef linux
unsetenv("TZ");
#else
putenv("TZ=");
#endif
tzset();
printf("_daylight = %d\n", _daylight);
printf("_timezone = %d\n", _timezone);
TZ2 = getenv("TZ");
if (! TZ2)
puts("TZ = NULL");
else
printf("TZ = %s\n", TZ2);
pZeit = localtime(&lZeit);
if (! pZeit)
printf("localtime(&%ld) is NULL\n", lZeit);
else
printf("localtime(&%ld) is %02d.%02d.%04d %02d:%02d:%02d\n",
lZeit,
pZeit->tm_mday,
pZeit->tm_mon + 1,
pZeit->tm_year + 1900,
pZeit->tm_hour,
pZeit->tm_min,
pZeit->tm_sec);
}
}
}
puts("please press ENTER");
fgets(buf, sizeof(buf), stdin);
return 0;
}