Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Converting a time string to seconds from the epoch

I have a string with the following format:

2010-11-04T23:23:01Z

The Z indicates that the time is UTC.
I would rather store this as a epoch time to make comparison easy.

What is the recomended method for doing this?

Currently (after a quck search) the simplist algorithm is:

1: <Convert string to struct_tm: by manually parsing string>
2: Use mktime() to convert struct_tm to epoch time.

// Problem here is that mktime uses local time not UTC time.
like image 873
Martin York Avatar asked Nov 09 '10 19:11

Martin York


2 Answers

Using C++11 functionality we can now use streams to parse times:

The iomanip std::get_time will convert a string based on a set of format parameters and convert them into a struct tz object.

You can then use std::mktime() to convert this into an epoch value.

#include <iostream>
#include <sstream>
#include <locale>
#include <iomanip>

int main()
{
    std::tm t = {};
    std::istringstream ss("2010-11-04T23:23:01Z");

    if (ss >> std::get_time(&t, "%Y-%m-%dT%H:%M:%S"))
    {
        std::cout << std::put_time(&t, "%c") << "\n"
                  << std::mktime(&t) << "\n";
    }
    else
    {
        std::cout << "Parse failed\n";
    }
    return 0;
}
like image 86
Martin York Avatar answered Sep 29 '22 12:09

Martin York


This is ISO8601 format. You can use strptime function to parse it with %FT%T%z argument. It is not a part of the C++ Standard though you can use open source implementation of it (this, for instance).

like image 28
Kirill V. Lyadvinsky Avatar answered Sep 29 '22 14:09

Kirill V. Lyadvinsky