c ++将没有时区的postgres时间戳转换为time_t [英] c++ convert postgres timestamp without time zone to time_t

查看:76
本文介绍了c ++将没有时区的postgres时间戳转换为time_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 libpq 库从 C++ 连接到 postgreSQL.我从 postgreSQL 请求并获取日期(没有时区的时间戳),但结果有一个我不知道如何修复的偏移量.

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 表:

Postgres table:

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

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

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

推荐答案

问题在于 ctime 使用本地时间,因此以偏移量结束.

The issue is that ctime uses localtime, so that ends up in the offset.

如果你想要 GMT,那么你应该使用 asctime(gmtime(&time)),它会给你一个不受当地时间影响的日期/时间.

If you want GMT, then you should use asctime(gmtime(&time)), which will give you a date/time without localtime influences.

ctime 相当于 asctime(localtime(&time))

这篇关于c ++将没有时区的postgres时间戳转换为time_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆