I’m trying to get the time in a different timezone (PST) using C++.
#define PST (-8);
char* Time::getSecondSystemTime() {
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = gmtime(&rawtime);
timeinfo->tm_hour = timeinfo->tm_hour + PST;
strftime(buffer, 80, "%I:%M %p", timeinfo);
std::string temp = std::string(buffer); // to get rid of extra stuff
std::string extraInfo = " Pacific Time ( US & Canada )";
temp.append(extraInfo);
return (char*) (temp.c_str());
}
The problem here is that when the GMT time is less than 8 hours (for example, right now, the time there is 3AM in the morning), subtracting 8 hours from it does not work!
What is the proper way to get time at a different time zone in Unix?
Since you said “UNIX”, this uses TZ, but,
TZ=[what goes here]You need to find out [what goes here] on your system. It might be “America/LosAngeles” or one of several other strings for PST.If your system is POSIX: TZ=PST8PST is guaranteed to work. But it may not be optimal.
Primitive non-production code assumes TZ is not currently in use. This is in C, not C++ since your tag was C: