Reputation: 1796
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
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