【问题标题】:Convert Date-Time to Milliseconds - C++ - cross platform将日期时间转换为毫秒 - C++ - 跨平台
【发布时间】:2017-01-15 05:46:36
【问题描述】:

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

【问题讨论】:

  • 从什么时候开始到毫秒??你的意思是 UNIX 纪元时间戳吗?
  • @GillBates 我会得到一个上述格式的字符串。
  • 是的,但这只是一个日期,你不能在不知道起点是什么的情况下将一些随机日期转换为毫秒。
  • @Will_Panda 他的意思是你使用哪个时代?计算毫秒数。就像 "20160907-05:00:54.123 是 123 ms 从 "20160907-05:00:54.000

标签: c++ posix


【解决方案1】:

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.

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

【讨论】:

  • 是的。这行得通,你是对的,我必须确保输入有效。但我一直在寻找更优雅的东西,而不是单独拆分每个元素。谢谢。
【解决方案2】:

没有 3rd 方库太糟糕了,因为 here is one(MIT 许可证)只是一个标头,可在 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&lt;std::chrono::milliseconds&gt; 是std::chrono::time_point&lt;std::chrono::system_clock, std::chrono::milliseconds&gt; 的类型别名。 IE。它来自system_clock::time_point 家族,只是milliseconds 精度。

完整记录:

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

没有比这更优雅的了。

【讨论】:

  • 这看起来是个不错的选择。但不幸的是我不能使用任何。
【解决方案3】:

鉴于您的字符串的格式,按如下方式解析它相当容易(尽管正则表达式或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 在 cmets 中正确指出的那样,Visual C++ 显然支持 get_time 有一段时间了,而且它的使用时间要短得多(请注意,小数秒需要以相同的方式处理)。

【讨论】:

  • 谢谢。是的,我打算选择这个选项,以防我找不到优雅的解决方案。
  • @Will_Panda :-) 不幸的是我同意——这不是最优雅的构造;更像是丑陋的棕色胶带。
  • 管道胶带仍然是管道胶带。 :)
  • 除了毫秒部分,std::get_time(&amp;when, "%Y%m%d-%H:%M:%S"); 看起来更干净。
  • @Mine 我同意(也在答案中写道);请注意,该问题未标记为 c++11。毫秒是一个固有问题,顺便说一句,tm 似乎没有亚秒字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
相关资源
最近更新 更多