Convert string time to UNIX timestamp

I have a line like 2013-05-29T21:19:48Z . I would like to convert it to the number of seconds from January 1, 1970 (UNIX era) so that I can save it using just 4 bytes (or maybe 5 bytes to avoid the 2038 problem). How can I do this in a portable way? (My code should work on both Linux and Windows.)

I can get the date parts from a string, but I don't know how to calculate the number of seconds. I tried to look at the documentation for date and time utilities in C ++ , but didn't find anything.

+7
source share
4 answers

use std :: get_time if you want to use C ++, but both options are also valid. strptime will ignore Z at the end - and T can be placed in a format string %Y-%m-%dT%H:%M:%s - but you can also just put Z at the end.

+4
source

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

+1
source

you can use boost date_time more specifically ptime . the only problem i see is T and Z in your line.

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

0
source

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); 
0
source

Source: https://habr.com/ru/post/1491690/


All Articles