Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ localtime when changing timezone

Tags:

c++

localtime

I have a setup working using localtime() to get a tm with the local times represented in it. And that is all good.

However, if I change timezone while the application is running, it does not notice that I have changed timezones.

Is there some way to tell it to 'go look again' to refresh to the system timezone?

I know this is probably not a common case, but it is what test are doing to test this feature, so they want it supported!

like image 914
Jon Avatar asked Jan 11 '12 17:01

Jon


1 Answers

Take a look at tzset (this is posix only). This might give you what you need. If your TZ environment variable is unset, it should reinitialize from the OS.

From the man page:

DESCRIPTION

The tzset() function initializes the tzname variable from the TZ environment variable. This function is automatically called by the other time conversion functions that depend on the time zone. In a SysV-like environment it will also set the variables timezone (seconds West of GMT) and daylight (0 if this time zone does not have any daylight savings time rules, non-zero if there is a time during the year when daylight savings time applies).

If the TZ variable does not appear in the environment, the tzname variable is initialized with the best approximation of local wall clock time, as specified by the tzfile(5)-format file localtime found in the system timezone directory (see below). (One also often sees /etc/localtime used here, a symlink to the right file in the system timezone directory.)

A simple test:

#include <iostream>
#include <time.h>
#include <stdlib.h>

int main()
{
        tzset();

        time_t t;
        time(&t);

        std::cout << "tz: " << tzname[0] << " - " << tzname[1] << " " << ctime(&t) << std::endl;

        setenv("TZ", "EST5EDT", 1);
        tzset();

        std::cout << "tz: " << tzname[0] << " - " << tzname[1] << " " << ctime(&t) << std::endl;

        return 0;
}

Gives me output:

tz: CST - CDT Wed Jan 11 12:35:02 2012

tz: EST - EDT Wed Jan 11 13:35:02 2012

like image 116
Nathan Ernst Avatar answered Oct 03 '22 07:10

Nathan Ernst