将日期时间转换为毫秒 - C++ - 跨平台

Convert Date-Time to Milliseconds - C++ - cross platform

我想将格式为“20160907-05:00:54.123”的字符串转换成毫秒。 我知道 strptime 在 Windows 中不可用,我想 运行 我的程序在 windows 和 linux。我也不能使用第三方库。 我可以标记字符串并转换它。但是有没有更优雅的方式,比如使用 strptime 来做到这一点?

鉴于字符串的格式,按如下方式解析它相当容易(尽管正则表达式或 get_time 可能更优雅):

tm t;
t.tm_year = stoi(s.substr(0, 4));
t.tm_mon = stoi(s.substr(4, 2));
t.tm_mday = stoi(s.substr(6, 2));
t.tm_hour = stoi(s.substr(9, 2));
t.tm_min = stoi(s.substr(12, 2));
t.tm_sec = 0;
double sec = stod(s.substr(15));

可以用 mktime:

找到自纪元以来的时间
mktime(&t) + sec * 1000

请注意,需要以不同方式处理小数秒 - 不幸的是,tm has only integer seconds

(查看完整代码 here。)


编辑

正如 Mine 和 Panagiotis Kanavos 在评论中正确指出的那样,Visual C++ 显然支持 get_time 很长一段时间,而且它的时间要短得多(请注意小数秒需要以相同的方式处理,虽然)。

std::sscanf呢?

#include <iostream>
#include <cstring>

int main() {
    const char *str_time = "20160907-05:00:54.123";
    unsigned int year, month, day, hour, minute, second, miliseconds;

    if (std::sscanf(str_time, "%4u%2u%2u-%2u:%2u:%2u.%3u", &year, &month,
               &day, &hour, &minute, &second,&miliseconds) != 7)
    {
        std::cout << "Parse failed" << std::endl;
    } 
    else
    {
        std::cout << year << month << day << "-" << hour << ":" 
                  << minute << ":" << second << "." << miliseconds
                  << std::endl;
    }
}

输出 (ideone): 201697-5:0:54.123.

但是,您应该确保输入有效(例如,日期可以在[0,99]范围内)。

没有第 3 方库太糟糕了,因为 here is one(MIT 许可证)只是一个 header,在 linux 和 Windows 上运行,并处理无缝毫秒:

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

int
main()
{
    date::sys_time<std::chrono::milliseconds> tp;
    std::istringstream in{"20160907-05:00:54.123"};
    date::parse(in, "%Y%m%d-%T", tp);
    std::cout << tp.time_since_epoch().count() << '\n';
}

这输出:

1473224454123

错误检查已为您完成。如果日期无效,流将 fail()

date::sys_time<std::chrono::milliseconds>std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> 的类型别名。 IE。它来自 system_clock::time_point 家族,仅 milliseconds 精度。

完整记录:

https://howardhinnant.github.io/date/date.html

没有比这更优雅的了。