无法验证从 time_point 到 tm 和 tm 返回 time_point 的转换

Can't verify the conversion from time_point to tm and tm back to time_point

本文关键字:tm time point 返回 转换 验证      更新时间:2023-10-16

我创建了一个当前的time_point,然后将其转换为结构TM并打印其值。现在将此TM结构转换为time_point。在比较第一个和第二个time_points时,它表明它们与众不同。但是结构的值是完全相同的。

有人可以发现,我做错了什么?

#include <iostream>
#include <ctime>
#include <chrono>
using namespace std;
using namespace std::chrono;
system_clock::time_point toTimePoint(struct tm tim)
{
    return std::chrono::system_clock::from_time_t(mktime(&tim));
}
tm toTm(system_clock::time_point tp)
{
    time_t tmt = system_clock::to_time_t(tp);
    struct tm * tim = localtime(&tmt);
    struct tm newTim(*tim);
    cout << "Info: " << tim->tm_mday << "/" << tim->tm_mon << "/" << tim->tm_year << " " << tim->tm_hour << ":" << tim->tm_min << ":" << tim->tm_sec << endl;
    cout << "Is Daylight saving: " << tim->tm_isdst << " wday: " << tim->tm_wday << " yday: " << tim->tm_yday << endl;
    return newTim;
}
int _tmain(int argc, _TCHAR* argv[])
{
    system_clock::time_point tp = system_clock::now();
    struct tm tmstruct = toTm(tp);
    system_clock::time_point newtp = toTimePoint(tmstruct);
    cout << "Time comparison: " << (tp == newtp) << endl;
    toTm(newtp);
}

输出:

信息:8/4/115 16:26:20是日光节省:0 wday:5 yday:127

时间比较:0

信息:8/4/115 16:26:20是夏令时节省:0 wday:5 yday:127

它正在舍入。time_point的分辨率比time_t更高。time_t只是秒,而time_point由系统定义。例如,在linux libstdc 上,它是纳秒。

作为一个例子,您所做的与下面的相似之处

  float f = 4.25;
  int i = (int)f; // i is 4
  std::cout << i << std::endl;
  float f2 = i; // f2 is 4.0 
  std::cout << (f == f2) << std::endl; // false
  int i2 = (int)f2; // i2 is also 4
  std::cout << i2 << std::endl;