Michael
Michael

Reputation: 43

Convert MySQL Datetime to C++ std::time_t

I am stuck in a problem and really hope you can help me. I like to convert a MySQL DATETIME field into a C++ std::time_t variable. My database looks like this:

CREATE TABLE data(
    id              INTEGER       AUTO_INCREMENT UNIQUE,
    path            VARCHAR(1000),
    acquisitionDate DATETIME
);

And I am trying to save the value from acquisitionDate into a c++ variable of type std::time_t.

After some web searching I learned that I have to use UNIX_TIMESTAMP in my MySQL statement. However, I did not understand how to actual use it. I can generate a query and receive a sql::ResultSet:

std::unique_ptr<sql::Statement> stmt(mConnection->createStatement());

std::string query="SELECT id, path, UNIX_TIMESTAMP(acquisitionDate) FROM data WHERE id = 1";

std::unique_ptr<sql::ResultSet> res(stmt->executeQuery(query));

But I don't understand how I can get the actual field value into a std::time_t variable

if(res->next())
{
    std::time_t acquisitionDate =  res->getInt("acquisitionDate");
    std::time_t acquisitionDate =  res->???
}

Somehow my brain does not get this last step. Please help me. Thank you very much!

Upvotes: 1

Views: 4903

Answers (2)

Michael
Michael

Reputation: 43

I also understood that it is possible to access the fields output by:

std::time_t acquisitionDate =  res->getInt("UNIX_TIMESTAMP(acquisitionDate)");

Or the SQL statement could rename the field:

SELECT UNIX_TIMESTAMP(acquisitionDate) AS foo FROM data WHERE id = 1

and then

std::time_t acquisitionDate =  res->getInt("foo");

However, casting should also be a good idea (after you have the correct field name):

std::time_t acquisitionDate =  static_cast<std::time_t>(res->getInt("foo"));

Upvotes: 2

Inline
Inline

Reputation: 2853

Just cast it

std::time_t acquisitionDate = (std::time_t)res->getInt("acquisitionDate");

Upvotes: 0

Related Questions