问题
I'm connecting from c++ to postgreSQL using libpq library. I request and obtain the date (timestamp without time zone) from postgreSQL, but the result has an offset that I don't know how to fix.
Postgres table:
id date
integer timestamp without time zone
29996 2014-02-28 23:59:00
result in C++ code:
id: 29996, Date: Sat Mar 01 10:59:00 2014
You can see that the date has the offset. Below is the code that I'm using. Any help will be greatly appreciated
PGconn *m_connection;
PGresult *res;
string strConn = "dbname=test host=localhost user=username password=secret";
m_connection = PQconnectdb(strConn.c_str());
string query = "SELECT id, extract(epoch from date)::bigint ";
query += "FROM table_test ORDER BY id DESC LIMIT 1";
// send query
res = PQexecParams(m_connection, query.c_str(), 0, 0, 0, 0, 0, 0);
string id = PQgetvalue(res, 0, 0);
unsigned char *data = (unsigned char*)PQgetvalue( res, 0, 1 );
unsigned int length = PQgetlength( res, 0 , 1 );
time_t time = _atoi64( (char*)data );
PQclear(res);
std::cout << "id:"<< id << ", Date: " << ctime(&time) << "\n";
回答1:
The issue is that ctime uses localtime, so that ends up in the offset.
If you want GMT, then you should use asctime(gmtime(&time)), which will give you a date/time without localtime influences.
ctime is the equivalent of asctime(localtime(&time))
来源:https://stackoverflow.com/questions/22208971/c-convert-postgres-timestamp-without-time-zone-to-time-t