【问题标题】:Date type displaying with timezone on node-postgres module在 node-postgres 模块上显示带有时区的日期类型
【发布时间】:2020-11-05 10:30:54
【问题描述】:

我已将输入数据以日期格式存储在 postgres 数据库中,但是当我在浏览器中显示日期时,它会显示带有时区的日期并将其从 utc 转换。例如,我以2020-07-16 格式存储了日期。但是当我显示日期时,它变成了2020-07-15T18:00:00.000Z。我尝试使用select mydate::DATE from table 仅获取日期,但它仍然显示带有时区的日期。我在我的节点应用程序中使用 node-postgres 模块。我怀疑这是 node-postgres 模块上的一些配置?来自他们的doc

node-postgres 将 DATE 和 TIMESTAMP 列转换为本地时间 在process.env.TZ中设置的节点进程的

他们有什么方法可以将其配置为仅解析日期吗?如果我像这样查询SELECT TO_CHAR(mydate :: DATE, 'yyyy-mm-dd') from table,我会得到2020-07-16,但为了获得日期,需要做很多工作

【问题讨论】:

  • 该列到底是什么数据类型? “格式”似乎表明它不是正确的date 列,而是text
  • 保存在日期数据类型列中
  • 然后 Node.js 把显示弄乱了
  • 我猜 node postgres 模块有问题

标签: node.js postgresql node-postgres


【解决方案1】:

这里写出来了:

https://node-postgres.com/features/types

日期/时间戳/时间戳记

console.log(result.rows)
// {
// date_col: 2017-05-29T05:00:00.000Z,
// timestamp_col: 2017-05-29T23:18:13.263Z,
// timestamptz_col: 2017-05-29T23:18:13.263Z
// }

bmc=# select * from dates;
  date_col  |      timestamp_col      |      timestamptz_col
------------+-------------------------+----------------------------
 2017-05-29 | 2017-05-29 18:18:13.263 | 2017-05-29 18:18:13.263-05
(1 row)

【讨论】:

    【解决方案2】:

    可以自己制作日期时间类型解析器:

    const pg = require('pg');
    pg.types.setTypeParser(1114, function(stringValue) {
      return stringValue;  //1114 for time without timezone type
    });
    
    pg.types.setTypeParser(1082, function(stringValue) {
      return stringValue;  //1082 for date type
    });

    类型id可以在文件中找到:node_modules/pg-types/lib/textParsers.js

    【讨论】:

      猜你喜欢
      • 2017-09-17
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多