Quantcast
Channel: Pete Ware » linux
Viewing all articles
Browse latest Browse all 7

Setting the timezone

$
0
0

I’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 <time.h>
#include <string>

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);


Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles





Latest Images