【问题标题】:Can't verify the conversion from time_point to tm and tm back to time_point无法验证从 time_point 到 tm 和 tm 到 time_point 的转换
【发布时间】:2015-07-19 06:40:51
【问题描述】:

我创建了一个当前时间点并将其转换为结构 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);
}

输出:

信息:115 年 8 月 4 日 16:26:20 是夏令时:0 wday:5 yday:127

时间比较:0

信息:115 年 8 月 4 日 16:26:20 是夏令时:0 wday:5 yday:127

【问题讨论】:

    标签: c++ std chrono ctime


    【解决方案1】:

    它是四舍五入的。 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;
    

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 1970-01-01
      • 2013-05-22
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多