【发布时间】:2016-07-26 11:13:58
【问题描述】:
我正在开发一个客户端-服务器自定义应用程序(将在 linux 上运行),我发送的其中一个帧包含一个时间戳(即发送帧的时间)。
为了使我的应用程序可靠,我使用gmtime 在客户端生成时间。我在比利时,所以现在客户端 VM 的时间比 UTC 时间晚 2 小时(因为夏季时间)。
在服务器端,我首先将收到的字符串转换为time_t 类型。我这样做是为了使用difftime 函数来查看时间戳是否太旧。
然后,我再次使用gmtime 生成时间戳(以UTC 时间表示),并将其转换为time_t。
然后我比较两个time_t 来查看时间差。
我在服务器端的时间转换有问题。 我使用和客户端一样的代码,但是输出的gmtime不一样...
客户端:函数生成时间戳,并将其导出为字符串(time_str):
std::string getTime()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime); // Get time of the system
timeinfo = gmtime(&rawtime); // Convert it to UTC time
strftime(buffer,80,"%d-%m-%Y %H:%M:%S",timeinfo);
std::string time_str(buffer); // Cast it into a string
cout<<"Time Stamp now (client) : "<<time_str<<endl;
return time_str;
}
它会产生这个(在当地时间 9 点 33 分):
现在时间戳:06-04-2016 07:33:30
服务器端: 获取时间戳、生成 newx 时间戳并进行比较的功能:
bool checkTimeStamp(std::string TimsStamp_str, double delay)
{
cout<<"TimeStamp recieved: "<<TimsStamp_str<<endl;
/* Construct tm from string */
struct tm TimeStampRecu;
strptime(TimsStamp_str.c_str(), "%d-%m-%Y %I:%M:%S", &TimeStampRecu);
time_t t_old = mktime(&TimeStampRecu);
/* Generate New TimeStamp */
time_t rawtime;
struct tm * timeinfo;
time (&rawtime); // Get time of the system
timeinfo = gmtime(&rawtime); // convert it to UTC time_t
time_t t2 = mktime(timeinfo); // Re-Cast it to timt_t struct
/* Convert it into string (for output) */
char buffer[80];
strftime(buffer,80,"%d-%m-%Y %H:%M:%S",timeinfo);
std::string time_str(buffer); // Cast it into a string
cout<<"Time Stamp now (server) : "<<time_str<<endl;
/* Comparison */
double diffSecs = difftime(t2, t_old);
cout<<diffSecs<<endl;
bool isTimeStampOK;
if (diffSecs < delay)
isTimeStampOK = true;
else
isTimeStampOK = false;
return isTimeStampOK;
}
它产生了这个(在比利时的 9 点 33 分):
收到的时间戳:06-04-2016 07:33:30
现在时间戳(服务器):06-04-2016 08:33:31
为什么服务器时间 (8h33) 既不是本地时间 (9h33),也不是 UTC 时间 (7h33)?
我在它的世代中犯了错误吗?我不明白在哪里,因为这些是与客户端完全相同的代码......
【问题讨论】:
-
我忘了说这两个虚拟机是本地时间,运行CentOS。
标签: c++ linux timestamp utc localtime