c++ convert postgres timestamp without time zone to time_t

拥有回忆 提交于 2020-12-11 02:52:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!