Talon06
Talon06

Reputation: 1796

Convert SQLite Date Field to C++ Time_T

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

YYYY-MM-DD HH:MM:SS

Upvotes: 1

Views: 2799

Answers (2)

user2530166
user2530166

Reputation:

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.

Upvotes: 2

CL.
CL.

Reputation: 180162

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.

Upvotes: 0

Related Questions