繁体   English   中英

将日期时间字符串解析成数字进行比较 C++

[英]Parsing date and time string into a number to compare C++

我的应用程序收到一个日期和时间字符串。 我需要能够解析这个字符串并将其与当前时间(以秒为单位)进行比较。

我将其解析为如下struct tm t以分别获取年、月、日、小时、分钟和秒。

    std::string timestr = "2020-12-18T16:40:07";
    struct tm t = {0};

    sscanf(timestr.c_str(), "%04d-%02d-%02dT%02d:%02d:%02d",
           &t.tm_year, &t.tm_mon,  &t.tm_mday,
           &t.tm_hour, &t.tm_min, &t.tm_sec);

我不确定是否需要将其转换为纪元时间,但是当我这样做时,我得到-1。 我不确定为什么。

time_t t_of_day;
t_of_day = mktime(&t);

我真的需要先将其转换为纪元吗?

我以秒为单位获取当前时间然后将其与我在t中获得的时间信息进行比较的最佳方法是什么? 谢谢。

只需使用chrono库的功能:

auto tp    = std::chrono::system_clock::from_time_t(std::mktime(&t));
auto epoch = std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());

但您不需要将其转换为纪元。 使用std::chrono::time_point比较,如:

auto tp    = std::chrono::system_clock::from_time_t(std::mktime(&t));
auto now   = std::chrono::system_clock::now();

std::cout << (tp == now) << std::endl;

你想要 C++ 解析:

https://en.cppreference.com/w/cpp/io/manip/get_time

std::stringstream timestr = "2020-12-18T16:40:07";
struct tm         t = {0};

timestr >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");

我应该注意到您的代码中有一个错误: tm_year与我们所知道的 year 不同。 这是自1900年以来的年数!

https://www.cplusplus.com/reference/ctime/tm/

所以你的代码需要另一行:

 t.tm_year -= 1900;

注意: std::get_time()已经做了补偿。

这可能是mktime()返回 -1 的原因,因为 3920 年超出范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM