Reputation: 6433
I'm using the official Mysql C++ driver and I'm attempting to read a mysql datetime string and parse it into a unix timestamp in c++.
I realize that I can use the unix_timestamp(column_name) function from within mysql, however, my specific instance requires that I parse the string from c++.
This is what I have attempted
static long UnixTimeFromMysqlString(std::string &s)
{
struct tm tmlol;
strptime(s.c_str(), "%Y-%m-%d %H:%M:%S", &tmlol);
time_t t = mktime(&tmlol);
return t;
}
The result that I am getting from this function does not appear to be correct. The input string is a standard mysql datetime string. Ex. 2013-06-06 13:37:42.
Does anybody have experience doing this? Thanks
Upvotes: 1
Views: 2372
Reputation: 19891
I think what you have already works - you can test it by looking at:
string str = "2013-06-06 16:06:00";
cout << UnixTimeFromMysqlString(str) << endl;
time_t current = time(NULL);
cout << current << endl;
When I ran it I got:
1370549160
1370549171
To see it as a string you can do:
time_t ret = UnixTimeFromMysqlString(str);
cout << "It is now " << ctime(&ret) << endl;
Which produces output:
It is now Thu Jun 6 16:06:00 2013
Upvotes: 1