Convert string time to UNIX timestamp

寵の児 提交于 2019-12-05 23:35:52

问题


I have a string like 2013-05-29T21:19:48Z. I'd like to convert it to the number of seconds since 1 January 1970 (the UNIX epoch), so that I can save it using just 4 bytes (or maybe 5 bytes, to avoid the year 2038 problem). How can I do that in a portable way? (My code has to run both on Linux and Windows.)

I can get the date parts out of the string, but I don't know how to figure out the number of seconds. I tried looking at the documentation of date and time utilities in C++, but I didn't find anything.


回答1:


use std::get_time if you want the c++ way - but both other options are also valid. strptime will ignore the Z at the end - and the T can be accomodated by format string %Y-%m-%dT%H:%M:%s - but you could also just put the Z at the end.




回答2:


Take a look at strptime(). For a Windows alternative, see this question.




回答3:


you could use boost date_time ore more specific ptime. the only problem i see is the T and Z in your string.

use ptime time_from_string(std::string) to init your time and long total_seconds() to get the seconds of the duration.




回答4:


Here is the working code

string s{"2019-08-22T10:55:23.000Z"};
std::tm t{};
std::istringstream ss(s);

ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S");
if (ss.fail()) {
    throw std::runtime_error{"failed to parse time string"};
}   
std::time_t time_stamp = mktime(&t);


来源:https://stackoverflow.com/questions/17681439/convert-string-time-to-unix-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!