PGsql + Koa DATE 日期变成 ISO 8601 格式

PGsql + Koa DATE 日期变成 ISO 8601 格式

koa 查询 PGSQL 日期时,日期自动转换成ISO 8601 格式的时间戳

我原本存入 2023-09-1,但是查询出来变成了 2023-08-31T16:00:00.000Z

我 PGsql 表

CREATE TABLE students (
  id VARCHAR PRIMARY KEY,
  name VARCHAR(50) NOT NULL,
  entrance_date DATE NOT NULL,
);

PostgreSQL 存储的 DATE 类型在数据库中是正确的 “2023-09-01”,但当通过 Node.js (Koa) 查询时,JavaScript 会自动将日期转换为 UTC 时区的 JavaScript Date 对象。

具体原因:

  1. PostgreSQL 中你正确存储了 “2023-09-01” 的日期
  2. 当 Node.js 从数据库读取这个 DATE 时,它转换为 JavaScript 的 Date 对象
  3. JavaScript Date 对象总是以 UTC 时间表示
  4. 如果你在中国(UTC+8 时区),“2023-09-01 00:00:00” 在 UTC 时间下就变成了 “2023-08-31T16:00:00.000Z”

因此 解决办法

第一种

const result = await pg.query(`SELECT * FROM students ORDER BY id DESC`)

// 处理日期格式
const formattedResult = result.map(student => ({
...student,
entrance_date: student.entrance_date ? student.entrance_date.toISOString().split('T')[0] : null,
graduation_date: student.graduation_date ? student.graduation_date.toISOString().split('T')[0] : null
}))

第二种

router.get("/students/list", async (ctx: Context) => {
  const result = await pg.query(`
    SELECT 
      id, name,
      TO_CHAR(entrance_date, 'YYYY-MM-DD') as entrance_date
    FROM students ORDER BY id DESC
  `)
  ctx.body = { code: 200, msg: "成功", data: result }
})
Licensed under CC BY-NC-SA 4.0
本博客已稳定运行
发表了57篇文章 · 总计29.26k字
使用 Hugo 构建
主题 StackJimmy 设计