You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL后端调用now()返回时间与pg-client差4小时问题求助

PostgreSQL调用now()函数不同客户端返回时间不一致问题

问题背景

PostgreSQL服务端配置时区为UTC,创建测试函数如下:

create function ufn_test_date() returns json
    language plpgsql
as
$$
declare    
    data_return json;    
begin    
    drop table if exists temp_date;
    create temp table temp_date as
    select now();
    ----------------------------------
    select json_agg(t)
    from (select sdc.*from temp_date sdc) t
    into data_return;
    return data_return;
    -----------------------------------
end
$$;

pg客户端直接执行结果

执行语句:select ufn_test_date();
返回结果:[{"now":"2021-09-21T10:49:53.272196+00:00"}]

后端代码调用执行结果

返回结果:[{"now":"2021-09-21T06:51:49.317205-04:00"}]
相关依赖版本:

  • 数据库连接库:Npgsql.EntityFrameworkCore.PostgreSQL 5.0.2
  • EF Core版本:Microsoft.EntityFrameworkCore 5.0.3
    两次返回时间相差4小时,仅部署单台PostgreSQL服务器。

修复方案

在配置数据库连接时显式指定时区为UTC即可,代码如下:

var dd_builder = new NpgsqlConnectionStringBuilder(connectString)
        {
            Timezone = "UTC"
        };
optionsBuilder.UseNpgsql(dd_builder.ToString());

内容的提问来源于stack exchange,提问作者Quân Vũ Quốc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:27:03