Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: Why the localtime display incorrectly in respect of its timezone?

Tags:

c++

c

timezone

I found that a strange behavior on C language recently but no idea why this happen.

when I use setenv(), set the TZ to GMT+1. the output of the local time will be one hour less than UTC time. (see the output)

actually, when I set the TZ to GMT-1. the output of the local time will be one hour more than UTC time.

This doesn't make sense. And if you don't believe, you can try the below code in C. Anyone knows this strange behavior? is it a bug?

Code:

int main(int argc, char** argv)
{
       time_t now;
       struct tm *local;
       setenv("TZ", "GMT+1", 1);
       tzset();
       now = time(NULL);
       //Get the Local time (GMT+1)
       local = localtime(&now);
       printf("Local time and date: %s\n", asctime(local));
       //Get the system time (GMT)
       local = gmtime(&now);
       printf("UTC time and date: %s\n", asctime(local));
       return 0;
}

Output:

Local time and date: Thu Aug  4 14:36:42 2011

UTC time and date: Thu Aug  4 15:36:42 2011
like image 863
TheOneTeam Avatar asked Aug 04 '11 15:08

TheOneTeam


1 Answers

It is indeed very confusing, but not a bug.

POSIX specifies this :

If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west (which may be indicated by an optional preceding '+' ).

So, it's basically the reverse of what you might expect.

like image 99
Sander De Dycker Avatar answered Oct 22 '22 03:10

Sander De Dycker