Cornel Verster
Cornel Verster

Reputation: 1781

c++ localtime to mysql datetime

I have a c++ time double that records seconds since 1 Jan 1970.

I want to convert this double and store it in a MySQL database, so here is my code to convert it firstly to a datetime format: *NOTE: ss.time is the double..

/* do the time conversion */
time_t rawtime;
struct tm * timeinfo;
rawtime = (time_t)ss.time;
timeinfo = localtime(&rawtime);

This code converts it to the following format: Thu Jul 24 05:45:07 1947

I then attempt to write it to the MySQL database as follows:

string theQuery = "UPDATE readings SET chng = 1, time = CAST('";
theQuery += boost::lexical_cast<string>(asctime(timeinfo));
theQuery += "' AS DATETIME) WHERE id = 1";

It does not work, but updates the time DATETIME variable in the table with NULL.

Can someone tell me how to do a correct conversion and update the SQL table?

Upvotes: 0

Views: 2545

Answers (1)

Marc B
Marc B

Reputation: 360702

Your c++ double is just a standard Unix timestamp, which MySQL can convert using its FROM_UNIXTIME function:

UDPATE ... SET ... time=FROM_UNIXTIME(rawtime)

Upvotes: 1

Related Questions