C ++时间字符串从时代转换到秒 [英] C++ Converting a time string to seconds from the epoch
问题描述
我有以下格式的字符串:
2010-11-04T23:23:01Z
块引用>在Z表示时间为UTC。结果
我宁愿存储此作为一个划时代的时间,使比较容易。什么是recomended方法这样做呢?
目前(后quck搜索)的simplist算法是:
1:<字符串转换为struct_tm:通过手动解析字符串>
2:使用mktime()根据转换struct_tm到划时代的时间。//这里的问题是,mktime使用本地时间不是UTC时间。
解决方案使用C ++ 11的功能,我们现在可以使用流来解析时间:
在了iomanip
的std :: GET_TIME
将根据一套格式参数转换为字符串,并将其转换成结构TZ
对象。您就可以使用
的std :: mktime()根据
将此转换成一个划时代的价值。的#include<&iostream的GT;
#包括LT&;&sstream GT;
#包括LT&;&现场GT;
#包括LT&;&了iomanip GT;诠释的main()
{
的std :: TM T = {};
的std :: istringstream SS(2010-11-04T23:23:01Z); 如果(SS>>的std :: GET_TIME(& T公司,%Y-%M-%胸苷%H:%M:%S))
{
性病::法院LT&;<的std :: put_time(& T公司,%C)<< \\ n
<<的std :: mktime(& T公司)LT;< \\ n;
}
其他
{
性病::法院LT&;< 解析失败\\ n;
}
}I have a string with the following format:
2010-11-04T23:23:01Z
The Z indicates that the time is UTC.
I would rather store this as a epoch time to make comparison easy.What is the recomended method for doing this?
Currently (after a quck search) the simplist algorithm is:
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.
解决方案Using C++11 functionality we can now use streams to parse times:
The iomanip
std::get_time
will convert a string based on a set of format parameters and convert them into astruct tz
object.You can then use
std::mktime()
to convert this into an epoch value.#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"; } }
这篇关于C ++时间字符串从时代转换到秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!