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

时间:2015-05-08 11:06:49

标签: c++ std chrono ctime

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

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

#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天:5天:127

时间比较:0

信息:8/4/115 16:26:20 夏令时:0天:5天:127

1 个答案:

答案 0 :(得分:0)

它正在四舍五入。 time_point的分辨率可能高于time_ttime_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;