将日期时间转换为毫秒-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
仅具有整数秒.
(请参见完整代码此处.)
修改
正如Mine和Panagiotis Kanavos在注释中正确指出的那样,Visual C ++显然支持get_time
相当长一段时间,并且它要短得多(请注意,小数秒需要以相同的方式处理). /p>
I want to convert a string in the format of "20160907-05:00:54.123" into milliseconds. I know that strptime is not available in Windows and I want to run my program in both windows and linux. I can't use third party libraries as well. I can tokenize the string and convert it. But is there a more elegant way like using the strptime to do so?
Given the format of your string, it is fairly easy to parse it as follows (although a regex or get_time
might be more elegant):
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));
Finding the time since the epoch can be done with mktime
:
mktime(&t) + sec * 1000
Note that the fractional seconds need to be handled differently - unfortunately, tm
has only integer seconds.
(See the full code here.)
Edit
As Mine and Panagiotis Kanavos correctly note in the comments, Visual C++ apparently supports get_time
for quite a while, and it's much shorter with it (note that the fractional seconds need to be handled the same way, though).
这篇关于将日期时间转换为毫秒-C ++-跨平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!