user842225
user842225

Reputation: 5989

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?

Upvotes: 3

Views: 7978

Answers (2)

Muhammad Usama
Muhammad Usama

Reputation: 180

The static Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, as per documentation here Date.now().

Whereas valid input for the time stamp types consists of the concatenation of a date and a time, followed by an optional time zone (if you are using timestamptz type instead of timestamp type), followed by an optional AD or BC. (Alternatively, AD/BC can appear before the time zone, but this is not the preferred ordering. You can read more about Date/Time types in pgSQL here.

In your case, you can do it like this

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

You'd use toISOString for sharing a date with another machine or process.

Upvotes: 2

alex1290
alex1290

Reputation: 31

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();
  }

Upvotes: 3

Related Questions