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.
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.
Take a look at strptime()
. For a Windows alternative, see this question.
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.
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