Shr*_*han 1 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());
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,当GMT时间少于8小时(例如,现在,早上3点的时间),从它减去8小时不起作用!
在Unix中的不同时区获取时间的正确方法是什么?
既然你说过"UNIX",那就是使用TZ,但是,TZ=[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.
Run Code Online (Sandbox Code Playgroud)