Posts Tagged ‘unix’
Setting the timezone
Wednesday, May 6th, 2009I’ve gotten pretty careful about keeping time in UTC and then converting it to localtime for the user to understand. For the first time, I actually had to find the localtime in a non-local timezone. It’s ugly. It seems you have to mess with the TZ environment variable. Here’s what I wrote:
include
include
std::string changeTimeZone (const std::string &tzname)
{
char *tzptr = getenv ("TZ");
std::string tzold;
if (tzptr)
tzold = tzptr;
if (tzname.empty())
unsetenv ("TZ");
else
setenv ("TZ", tzname.c_str(), 1);
tzset();
return tzold;
}
And here’s a code fragment that uses it:
std::string oldzone = changeTimeZone("US/Pacific");
time_t seconds = ::time(0);
struct tm tm_time;
localtime_r (&seconds, tm_time);
changeTimeZone(oldzone);