我正在尝试使用 C++ 获取不同时区 (PST) 的时间。
#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());
}
这里的问题是,当GMT时间小于8小时时(比如现在凌晨3点),减去8小时是不行的!
在 Unix 中获取不同时区时间的正确方法是什么?
最佳答案
既然你说的是“UNIX”,这就使用了 TZ,但是,TZ=[what goes here]
你需要找出你系统上的[what goes here]。它可能是“America/LosAngeles”或 PST 的其他几个字符串之一。
如果您的系统是 POSIX:TZ=PST8PST 保证可以工作。但这可能不是最优的。
原始非生产代码假定 TZ 当前未在使用中。这是在 C 中,而不是 C++,因为你的标签是 C:
setenv("TZ", "PST8PST", 1); // set TZ
tzset(); // recognize TZ
time_t lt=time(NULL); //epoch seconds
struct tm *p=localtime(<); // get local time struct tm
char tmp[80]={0x0};
strftime(tmp, 80, "%c", p); // format time use format string, %c
printf("time and date PST: %s\n", tmp); // display time and date
// you may or may not want to remove the TZ variable at this point.
关于c++ - Unix C++ : get time at a different zone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14049047/