C ++自定义时间日期结构到utc纪元

时间:2017-12-19 13:50:42

标签: c++ c++11 timestamp chrono time-t

我使用一个使用以下结构的库来定义开始时间戳,如下所示。

{
        "remote_server": {
                "url": "https://notary-server:4443"**,
                "root_ca": "root-ca.crt"
        }
}

对于此时间之后的每个日志条目,以与第一个时间戳的纳秒差异指定。

让我们说它的UTC 2017-12-19 14:44:00 此后的第一个日志条目是397000ns。

如何从第一个SYSTEMTIME结构的epoch创建chronos,time_t或unix时间,然后将纳秒添加到它。

打印输出应该是第一次输入 2017-12-19 14:44:00.000397

祝你好运

2 个答案:

答案 0 :(得分:1)

<强>更新

我稍微修改了以下代码,以便在SYSTEMTIMEdate::sys_time<std::chrono::milliseconds>之间进行转换,而不是date::sys_time<std::chrono::nanoseconds>

原理:因此to_SYSTEMTIME中没有隐式精度损失。 to_SYSTEMTIME的客户可以以他们想要的任何方式明确地截断精度(floorroundceil等。未能截断精度(如果需要)不会成为静默运行时错误。

客户端代码(main)不受此更改的影响。

您可以使用Howard Hinnant's free, open-source, header-only date/time library

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

using WORD = int;

struct SYSTEMTIME {
    /** year */
    WORD year;

    /** month */
    WORD month;

    /** day of week */
    WORD dayOfWeek;

    /** day */
    WORD day;

    /** hour */
    WORD hour;

    /** minute */
    WORD minute;

    /** second */
    WORD second;

    /** milliseconds */
    WORD milliseconds;
};

date::sys_time<std::chrono::milliseconds>
to_sys_time(SYSTEMTIME const& t)
{
    using namespace std::chrono;
    using namespace date;
    return sys_days{year{t.year}/t.month/t.day} + hours{t.hour} +
           minutes{t.minute} + seconds{t.second} + milliseconds{t.milliseconds};
}

int
main()
{
    using namespace std::chrono;
    using namespace date;
    SYSTEMTIME st{2017, 12, 2, 19, 14, 44, 0, 0};
    auto t = to_sys_time(st) + 397000ns;
    std::cout << floor<microseconds>(t) << '\n';
}

输出:

2017-12-19 14:44:00.000397

通过收集SYSTEMTIME中的不同部分,将std::chrono::time_point<system_clock, milliseconds>转换为date::sys_time<milliseconds>(其类型别名为SYSTEMTIME)。然后,只需将nanoseconds添加到time_point,将其截断为所需的microseconds精度,然后将其流出。

如果它有用,可以使用相同的库进行相反的转换:

SYSTEMTIME
to_SYSTEMTIME(date::sys_time<std::chrono::milliseconds> const& t)
{
    using namespace std::chrono;
    using namespace date;
    auto sd = floor<days>(t);
    year_month_day ymd = sd;
    auto tod = make_time(t - sd);
    SYSTEMTIME x;
    x.year = int{ymd.year()};
    x.month = unsigned{ymd.month()};
    x.dayOfWeek = unsigned{weekday{sd}};
    x.day = unsigned{ymd.day()};
    x.hour = tod.hours().count();
    x.minute = tod.minutes().count();
    x.second = tod.seconds().count();
    x.milliseconds = tod.subseconds().count();
    return x;
}

答案 1 :(得分:0)

您可以使用new Circle(x, y, dx, dy, radius, color); 中的mktime()<ctime>转换为tm,这是一个整数类型。

time_t与您的tm结构非常相似。因此,您可以轻松地来回翻译它们。

将您的结构转换为tm,然后像这样使用SYSTEMTIME

gmtime()

有关详细信息,请参阅以下链接:

struct tm

time_t

mktime