Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string time to UNIX timestamp

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.

like image 689
svick Avatar asked Jul 16 '13 15:07

svick


People also ask

How do you convert date string to epoch time?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How is Unix timestamp calculated?

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).

What is Unix timestamp format?

Unix epoch timestamps are supported in the following formats: 10 digit epoch time format surrounded by brackets (or followed by a comma). The digits must be at the very start of the message. For example, [1234567890] or [1234567890, other] followed by the rest of the message.

Is Unix time UTC?

Unix time is the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970, excluding leap seconds. This time is named the Unix epoch, because it is the start of the Unix time. Unix time is not a true representation of UTC, because leap seconds are not independently represented.


2 Answers

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.

like image 120
Iwan Aucamp Avatar answered Sep 20 '22 21:09

Iwan Aucamp


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);
like image 28
Joanna Avatar answered Sep 22 '22 21:09

Joanna