如何修复PostgreSQL和NodeJS/NestJS应用程序之间的DateTime和TimeZone问题?

yfwxisqw  于 11个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(123)

我有一个Postgres数据库和一个nodeJS应用程序(NestJS框架,为了完整起见)。我需要帮助解决时区问题。
这是我的博客文章存储表:

create table if not exists public.posts
(
    id      serial constraint "PK_40808690ebab9150a6558c0f82c" primary key,
    created_at      timestamp default now() not null,
    last_updated_at timestamp default now(),
    title   varchar(256),
    pub_date  timestamp,
    ...
 )

字符串
首先,我想查询所有帖子的最新日期:

select max(pub_date)::date from posts;

-> 2023-11-05


然后我想查询该特定日期的所有博客文章:
Postgres CLI中,执行以下查询

select * from daily where pub_date::date = '2023-11-05'::date;


将返回2023-11-05发布的所有帖子:
x1c 0d1x的数据
然而,当我从基于NodeJS的后端执行查询时,利用第一个查询的返回值,将其作为参数传递给第二个查询,它不会像预期的那样工作。
将第一个查询的结果传递到后端将返回与前一天不同的日期:

const sql = 'select max(pub_date)::date from posts';
const d = await this.repository.query(sql);
console.log('D', d);


这将收到一个日期,显示预产期前一天(或确切的预产期前1小时23分钟):

D [ { max: 2023-11-04T23:00:00.000Z } ]


当我使用此值执行上述其他查询以检索该特定日期的所有帖子时,它将不起作用,因为它查询的是2023-11-05 = 2023-11-04之前一天的帖子
我想这和某种奇怪的时区魔法有关。
使用PostgreSQL CLI(或任何数据库工具,如pgAdmin)将返回正确的值。我的nodeJS后端将返回错误的日期。我使用TypeORM和postgresql-extension。
我该怎么补救?

svmlkihl

svmlkihl1#

检查并更正您的客户端set timezone='utc';和/或使用at time zone来明确说明这些日期应该在哪里匹配,然后向下转换为date。此外,看看您是否可以合并这两个查询,从而节省往返时间:demo

select current_setting('timezone') as client_timezone,* 
from daily 
where             (pub_date at time zone 'utc')::date
     = (select max(pub_date at time zone 'utc')::date from posts);

字符串

相关问题