user1065276
user1065276

Reputation: 317

Time based on time zone in C++

What is the difference between gmtime() and localtime() ? My requirement: I need to display the time as per the time zone of my place. I have a time in POSIX(UTC) format in seconds. i have time zone offset(between UTC and my current place) in seconds. I either add or subtract the time zone offset. After this i still have the time in POSIX format. In order to convert it to human time, should I use gmtime() or localtime(). this is because i need the date too. Please clarify. Thanks!

Upvotes: 2

Views: 1819

Answers (2)

thiton
thiton

Reputation: 36049

You shouldn't provide the time zone offset yourself, but rather a real time zone specification via the environment. Then, localtime will give you the localized time. (gmtime always gives you UTC.) Suppose your code looks like

struct tm time_buffer, *localtime;
localtime = localtime_r(timep, &time_buffer);
printf("The hour is %i\n", localtime->tm_hour);

, then you call your program via:

$ TZ=Europe/Berlin my-program

and get the local hour of Berlin, correctly adjusted for daylight saving time.

If you absolutely need to provide a timezone yourself, read man tzset.

Upvotes: 1

James Kanze
James Kanze

Reputation: 153919

gmtime is UTC—coordinated universal time. It is always the same, everywhere. localtime is an interpretation of the local time, as determined by the time zone and whether summer time is in effect or not. The time zone will be determined by the environment variable TZ, which the user should have set to his local timezone; if this variable is not set, an implementation defined default is used: typically the timezone where the machine is located.

Upvotes: 0

Related Questions