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

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

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

    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;
};

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

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

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

打印输出应该是2017-12-19 14:44:00.000397的第一个条目

最好的祝福

c++ c++11 timestamp chrono time-t
2个回答
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;
}

0
投票

您可以使用mktime()中的<ctime>tm转换为time_t,这是一个整数类型。

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

将你的结构转换为tm然后像这样使用tm

SYSTEMTIME

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

gmtime()

#include <ctime> struct tm time = fromSystemtime(...); time_t timestamp; timestamp = mktime(&time);

struct tm

© www.soinside.com 2019 - 2024. All rights reserved.