c++ - Unix C++ : get time at a different zone

标签 c++ unix timezone unix-timestamp timezone-offset

我正在尝试使用 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(&lt); // 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/

相关文章:

c++ - 为嵌入式 Linux 应用程序交叉编译 Qt

c++ - 运算符优先级.. () 和++

c++ - 如何在 C++ 中跟踪 BFS 深度

perl - 部署脚本需要更新配置文件中的整数

python - 如何根据 Python 中的日期(而不是当前语言环境)将 DateTime 转换为夏令时

date - 以 UTC 存储时间总是一个好主意,还是在这种情况下以本地时间存储更好?

c++ - 数组排序,从高到低

bash - Unix 脚本无法更改 Ubuntu 上的 postgres hba.conf 配置文件

c++ - 如何忽略 umask 以创建具有给定权限的文件

java - 使用 Java 和 Spring 在 Oracle 数据库中插入 UTC/GMT 日期