2014-03-05 44 views
1

我使用libpq库从C++连接到postgreSQL。我请求并从postgreSQL获取日期(没有时区的时间戳),但结果有一个我不知道如何解决的偏移量。c + +将postgres时间戳无时区转换为time_t

Postgres的表:

id    date 
integer   timestamp without time zone 
29996   2014-02-28 23:59:00 

结果在C++代码:

id: 29996, Date: Sat Mar 01 10:59:00 2014 

您可以看到日期的偏移量。以下是我正在使用的代码。任何帮助将不胜感激

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"; 

回答

0

的问题是,ctime使用本地时间,所以,在偏移结束。

如果你想要格林威治标准时间,那么你应该使用asctime(gmtime(&time)),这会给你一个没有本地时间影响的日期/时间。

ctimeasctime(localtime(&time))

+0

感谢相当于!它工作完美 – miguel