【问题标题】:Save Date.now() to timestamp column but get date/time field value out of range将 Date.now() 保存到时间戳列,但日期/时间字段值超出范围
【发布时间】:2022-07-22 19:31:28
【问题描述】:

我的项目(带有 TypeScript 的 NestJS)在 PostgreSQL 数据库上使用 TypeOrm

我的表有一个列(在迁移文件中):

new TableColumn({
   name: 'managed_at',
   type: 'timestamp',
   isNullable: true,
 }),

实体类中的关联字段:

  @Column({ type: 'timestamp', nullable: true })
  managedAt: Date | null;

我希望 managed_at 列保存日期和时间的值。

如果我将数据保存到表中:

import { Repository } from 'typeorm';
...
// repo is the Repository of typeorm
repo.update(
    { managedAt: Date.now() }
  );

我得到错误:

 QueryFailedError: date/time field value out of range: "1651495656811"

如何解决使用 Date.now() 保存数据和时间值的问题?

【问题讨论】:

    标签: postgresql typeorm node.js-typeorm


    【解决方案1】:
    import { Repository } from 'typeorm';
    ...
    // repo is the Repository of typeorm
    repo.update(
        { managedAt: new Date() }
      );
    

    更改 Date.now() -> 新的 Date()。 您需要将日期类型的数据保存到时间戳类型的列中。

    顺便说一句,您可以在实体类中添加它。 它会在更新数据之前更新列。

      @BeforeUpdate()
      updateManagedAt(): void {
        this.managedAt = new Date();
      }
    

    【讨论】:

      【解决方案2】:

      静态 Date.now() 方法返回自 1970 年 1 月 1 日 00:00:00 UTC 以来经过的毫秒数,根据此处的文档 Date.now()

      而时间戳类型的有效输入包括日期和时间的串联,后跟可选的时区(如果您使用的是 timestamptz 类型而不是时间戳类型),然后是可选的 AD 或 BC。 (或者,AD/BC 可以出现在时区之前,但这不是首选顺序。 您可以在 pgSQL here 中阅读有关日期/时间类型的更多信息。

      在你的情况下,你可以这样做

          repo.update({ managedAt: (new Date()).toISOString() });
      

      您可以使用 toISOString 与另一台机器或进程共享日期。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-25
        • 2011-12-22
        • 1970-01-01
        • 2012-06-12
        相关资源
        最近更新 更多