1

How Do I Convert A SQLite Date in the following format to a C++ Time_T Variable?

YYYY-MM-DD HH:MM:SS
Talon06
  • 1,756
  • 3
  • 27
  • 51

2 Answers2

2

You may wish to read this question, which discusses a few approaches. In particular, if you have access to Boost, you can use <boost/date_time/posix_time/posix_time.hpp> and create a boost::posix_time::ptime object from a string of the format in your question. (See the first answer in that question.)

Alternatively, you can use strptime().

Example:

#include <ctime>
#include <iostream>

std::size_t timestamp_to_seconds(const char* timestamp)
{
    std::tm tm_struct;

    strptime(timestamp, "%Y-%m-%d %H:%M:%S", &tm_struct);
    // You can control daylight savings time if necessary.
    tm_struct.tm_isdst = 1;
    std::size_t t = std::mktime(&tm_struct);

    return t;
}

int main()
{
    std::cout << timestamp_to_seconds("2013-07-05 12:34:56") << std::endl;

    return 0;
}

Running this example gives the following output:

$ ./a.out
1373042096
$ date -d "2013-07-05 12:34:56" +%s
1373042096

As you can see, it agrees with the date utility. (I assuming you are on a platform with access to strptime.) You may have to be careful when handling daylight savings or timezone info...I had to use tm_struct.tm_isdst = 1 to force recognition of daylight savings and get agreement with date.

Community
  • 1
  • 1
  • Is there a better date time type function for C++ I am very new to the language and time_t was the first thing I found. I tried using the boost library, but when trying to use it I get a lot of compile errors. I don't know if it is the library or my lack of understanding. – Talon06 Jul 05 '13 at 21:06
  • Hi Talon06, please see my edit for a short example. Hopefully you can modify it to suit your exact purposes. –  Jul 06 '13 at 00:35
0

time_t is a Unix timestamp (seconds since 1970-01-01), so you have to convert with strftime:

SELECT strftime('%s', '2013-07-05 12:34:56');

The result is a string, but you can read it as an integer value.

CL.
  • 173,858
  • 17
  • 217
  • 259
  • Is there anyway to do this in the application or do I need to query against that database? – Talon06 Jul 05 '13 at 18:01
  • It might be a good idea to store the dates in the database in the `time_t` format in the first place. If you really want to convert them inside your program, see RyanMck's answer. – CL. Jul 05 '13 at 19:10
  • Yes, it was a little unclear whether the conversion was supposed to take place via C++ or SQLite. Certainly the SQLite conversion is a easier. –  Jul 05 '13 at 19:24