将带有参考时间的时间戳转换为格式化时间

问题描述 投票:0回答:1

我想将时间戳转换为格式化时间。时间戳记是一个双精度值(例如,时间戳记= 41274.043),其引用日期为1.1.1900 00:00,应返回类似02.01.2017 01:01的内容。

我找不到有关如何正确设置参考时间的任何信息。有什么建议吗?要自定义日期,我将使用strftime(),必须使用STL ...

BR

jtotheakob

c++ date-conversion
1个回答
0
投票

使用Howard Hinnant's free, open source, header-only library可以这样完成:

#include "date/date.h"
#include <iostream>

std::chrono::system_clock::time_point
to_chrono_time_point(double d)
{
    using namespace std::chrono;
    using namespace date;
    using ddays = duration<double, days::period>;
    return sys_days{January/1/1900} + round<system_clock::duration>(ddays{d});
}

int
main()
{
    std::cout << date::format("%d.%m.%Y %H:%M\n", to_chrono_time_point(41274.043));
}

这简单地将double转换为具有chrono::duration表示和周期doubledays,然后将duration舍入为system_clock::duration,最后将该持续时间添加到1.1.1900 00:00。结果为std::chrono::system_clock::time_point

std::chrono::system_clock::time_point可以用如图所示的同一库中的date::format格式化。该程序的输出是:

02.01.2013 01:01
© www.soinside.com 2019 - 2024. All rights reserved.