C 自定义时间日期结构到UTC时期

C++ custom time date struct to utc epoch

本文关键字:UTC 时期 结构 日期 自定义 时间      更新时间:2023-10-16

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

    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此后的第一个日志条目是397000n。

如何从第一个SystemTime struct的时期创建计时,time_t或unix时间,然后将纳秒添加到它。

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

最好的问候

更新

我已经对下面的代码进行了稍作修改,以在SYSTEMTIMEdate::sys_time<std::chrono::milliseconds>之间转换,而不是date::sys_time<std::chrono::nanoseconds>

理由:,因此to_SYSTEMTIME中没有隐含的精度损失。to_SYSTEMTIME的客户端可以以任何他们想要的方式明确截断精度(floorroundceil等)。并且未能截断精度(如果需要的话)不会是无声的运行时间错误。

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


您可以使用霍华德·辛南特(Howard Hinnant)的免费,开源,仅标题的日期/时间库:

#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>的类型ALIAS),通过从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 = weekday{sd}.c_encoding();
    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;
}

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

tm与您的SYSTEMTIME结构相似。因此,您应该可以轻松地来回翻译它们。

将您的结构转换为TM,然后将gmtime()这样。

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

有关更多详细信息,请参见以下链接:

结构TM

time_t

MKTime