【问题标题】:How can I create columns with type Date and type DateTime in nestjs with typeORM?如何使用 typeORM 在 Nestjs 中创建类型为 Date 的列并键入 DateTime?
【发布时间】:2020-10-23 01:40:11
【问题描述】:

我是 Nestjs 的新手。如何设置接受日期格式和日期时间格式的列?

不是在这两种情况下,列是两个不同的列,一个接受日期,另一个接受日期时间。

【问题讨论】:

    标签: mysql date orm nestjs typeorm


    【解决方案1】:

    您可以查看说明 @Column 装饰器的文档 here。在 @Column 中有一个名为 type 的选项 -> 您可以在此处指定要为该特定列存储的日期类型。

    更多关于列类型here

    例如(使用PostgreSQL):

    @Column({ type: 'date' })
    date_only: string;
    
    @Column({ type: 'timestamptz' }) // Recommended
    date_time_with_timezone: Date;
    
    @Column({ type: 'timestamp' }) // Not recommended
    date_time_without_timezone: Date;
    

    请注意,date_onlystring 类型。请参阅this issue 了解更多信息。

    希望对你有帮助:)

    【讨论】:

    • 这个答案不正确。 typeorm 为 type: 'date' 返回的类型是字符串 - 不是时间设置为 0 的日期对象。请参阅 github.com/typeorm/typeorm/issues/2176
    • @sarfata 我已经更新了我的答案。让我知道你的想法!
    • @CarloCorradini 太棒了!我喜欢你也明确推荐timestamptz ;)
    • 使用mysql时时间戳可以吗?因为不支持 timestamptz?
    【解决方案2】:

    怎么样?

    @CreateDateColumn()
    created_at: Date;
        
    @UpdateDateColumn()
    updated_at: Date;
    

    编辑

    您可以找到更多信息here

    【讨论】:

      【解决方案3】:

      要为这张票添加更多内容,因为甚至没有提到 DateTime:

        /**
         * Start DateTime
         */
        @Column({
          type: 'datetime',
          default: () => 'NOW()',
        })
        @Index()
        start: string;
      
        /**
         * End DateTime
         */
        @Column({
          type: 'datetime',
          nullable: true,
        })
        @Index()
        end: string;
      

      这是给那些不想或不需要使用的人

      @CreateDateColumn()

      @UpdateDateColumn()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-12
        • 2021-06-27
        • 2021-08-28
        • 1970-01-01
        • 2019-03-11
        • 2022-01-01
        • 1970-01-01
        • 2021-07-15
        相关资源
        最近更新 更多