'Save Date.now() to timestamp column but get date/time field value out of range

My project (NestJS with TypeScript) is using TypeOrm on PostgreSQL database.

My table has a column (in migration file):

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

Associated field in entity class:

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

I would like the column managed_at holds value of date and time.

If I save a data to the table with:

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

I get error:

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

How to solve this problem that using Date.now() and hold value of data and time?



Solution 1:[1]

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

Change Date.now() -> new Date(). You need to save Date type data to column in timestamp type.

Btw, you can add this in your entity class. It will update column before update data.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alex1290