另一个时区的日期:Linux上的C++

Rog*_*ore 6 c++ linux timezone date

有没有办法得到日期...最好是YYYYMMDD格式...在澳大利亚/悉尼时区(不仅仅是GMT + 11).....在Linux上通过C++?

谢谢,

罗杰

Pet*_*esh 4

是的,但您只需使用标准 c 库机制。

通过创建字符串来设置环境中所需的时区:

std::string tz = "Australia/Sydney";
setenv("TX", const_cast<char *>(tz.c_str()), 1);
tzset(); // Initialize timezone data
time_t aTime = time(NULL); // get the time - this is GMT based.
struct tm retTime;
localtime_r(&aTime, &retTime); // Convert time into current timezone.
char destString[1024];
strftime(destString, 1023, "%Y%m%d %Z", &retTime); // Format the output in the local time.
std::cout << destString << std::endl;
Run Code Online (Sandbox Code Playgroud)

问题是这段代码不是线程安全的 - 多个线程更改时区信息的结果并不好。

这个答案为您提供了一种使用 boost 来做到这一点的方法,这肯定要容易得多。