Mar*_*ork 11 c c++ time platform-independent
我有一个字符串,格式如下:
2010-11-04T23:23:01Z
Z表示时间是UTC.
我宁愿将其存储为一个时间点,以便比较容易.
这样做的推荐方法是什么?
目前(在quck搜索之后),简化算法是:
1: <Convert string to struct_tm: by manually parsing string>
2: Use mktime() to convert struct_tm to epoch time.
// Problem here is that mktime uses local time not UTC time.
Run Code Online (Sandbox Code Playgroud)
使用C++ 11功能,我们现在可以使用流来解析时间:
iomanip std::get_time将根据一组格式参数转换字符串并将其转换为struct tz对象.
然后,您可以使用std::mktime()它将其转换为纪元值.
#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>
int main()
{
std::tm t = {};
std::istringstream ss("2010-11-04T23:23:01Z");
if (ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S"))
{
std::cout << std::put_time(&t, "%c") << "\n"
<< std::mktime(&t) << "\n";
}
else
{
std::cout << "Parse failed\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)