c++ - 以毫秒精度对日期和时间进行操作

标签 c++ datetime

我需要获取当前本地时间(包括毫秒)并将其传递给某个嵌入式设备。这个设备现在有了日历时间的想法,但有自己的计时器,精度为 1 毫秒。因此,当此设备收到当前时间戳时,它会打开日志文件并将此时间戳写入开头。从现在开始,它将不同的消息写入日志,每条消息都包含从初始时间开始经过的毫秒数。最后,嵌入式设备日志文件被上传到主机并进行解析,所有相对时间间隔都转换回完整的日历时间。主机程序的第一部分如下所示:

struct timestamp
{
    int year;    // 0-based 
    int month;   // [1-12]
    int day;     // [1-31]
    int hour;    // [0-23]
    int minute;  // [0-59]
    int sec;     // [0-59]
    int ms;      // [0-999]
};

timestamp time_point_to_timestamp(std::chrono::time_point<std::chrono::system_clock> tp)
{
    auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(tp);
    auto fraction = tp - seconds;
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
    time_t tt = std::chrono::system_clock::to_time_t(tp);
    tm* ptm = localtime(&tt);

    timestamp t;
    t.year = ptm->tm_year + 1900;
    t.month = ptm->tm_mon + 1;
    t.day = ptm->tm_mday;
    t.hour = ptm->tm_hour;
    t.minute = ptm->tm_min;
    t.sec = ptm->tm_sec;
    t.ms = static_cast<int>(milliseconds.count());
    return t;
}

void start()
{
     timestamp ts = time_point_to_timestamp(std::chrono::system_clock::now());
     // send ts to embedded device
     // ...
}

现在,当我将日志从设备返回到主机时,它看起来像这样:

2018 6 24 8 25 52 598     // start time ts
500 message 1             // ms elapsed from ts
2350 message 2            // ms elapsed from ts
...

我需要解析这个文件并转换每条消息,打印它的完整日期和时间。例如,500 将转换为:

2018 6 24 8 25 53 098

所以,我需要一些方法将 timestamp 转换为任何 C++ 类型,允许为其添加时间间隔(time_pointduration ?),并以人类可读的形式打印出来。我的编译器支持 C++14。

最佳答案

我会这样做:

int64_t to_epoch_ms(time_point<system_clock> tp)
{
    return duration_cast<milliseconds>(tp.time_since_epoch()).count();
}

然后将自纪元以来的毫秒数传递给设备,在那里它可以被记录为例如1529819166927。添加毫秒既简单又快速,无论您是直接使用 int64_t 还是通过转换回 time_point 来完成:

time_point<system_clock> from_epoch_ms(int64_t ms)
{
    return {milliseconds(ms)};
}

auto tp1 = from_epoch_ms(ms + 123);
auto tp1 = from_epoch_ms(ms) + milliseconds(456);

关于c++ - 以毫秒精度对日期和时间进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51007219/

相关文章:

c++ - 如何创建具有电视效果的图像?

c++ - 'std' 以外的 C++ 中有用的命名空间

c++ - 变量如何既是 constexpr 又不是 constexpr?

c++ - Linux 上 X11 图形库的声明问题

Java/MongoDB 按日期查询

python - 为什么 Python 的 weekday() 与 C 中的 tm_wday 不同?

c++ - 为什么我无法接收 C++ 中的字符

php - laravel 中返​​回的时间不正确

python - 将时间数据 CSV 拆分为不同的年份并将它们绘制在一张图中

python - Pandas to_datetime 函数给出不稳定的输出