9

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.

svick
  • 236,525
  • 50
  • 385
  • 514
  • 2
    Have you tried anything? – Rapptz Jul 16 '13 at 15:59
  • @Rapptz See update. I tried looking at the documentation, but didn't find anything. – svick Jul 16 '13 at 16:01
  • C++ doesn't have good date/time utilities like other languages such as C#. Your best bet is probably to find something in the [Boost libraries](http://www.boost.org/doc/libs/) which are applicable to your situation. – Rapptz Jul 16 '13 at 16:03
  • Whether you're on Windows or Linux, an answer that mentions solutions for both (including boost) is http://stackoverflow.com/questions/321849/strptime-equivalent-on-windows – Tony Delroy Jul 16 '13 at 16:07

4 Answers4

7

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);
Joanna
  • 153
  • 1
  • 6
4

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.

Iwan Aucamp
  • 1,469
  • 20
  • 21
  • 2
    But that doesn't return UNIX timestamp. – svick Jul 16 '13 at 20:23
  • 1
    Please consider making your answer more holistic, e.g. explaining about std::locale, facets and whether mktime heads time zones or not, and so on. – mxmlnkn Jul 13 '17 at 19:00
1

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

Community
  • 1
  • 1
freitass
  • 6,542
  • 5
  • 40
  • 44
0

You could use boost date_time ore more specific ptime.

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

user1810087
  • 5,146
  • 1
  • 41
  • 76