Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current date in TypeORM and PostgreSQL

What's the best way to have a field for a date in PostgreSQL and TypeORM?

I'm relatively new in PostgreSQL (in general SQL database), but in MongoDB (with Mongoose) I usually have a field like this:

export class User {
  @Prop({ default: Date.now() })
  createdAt: Date;
}

What would be the equivalent to this in TypeORM and PostgreSQL? Because, if I use this approach, PostgreSQL throws me an error.

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

like image 689
Angel Martinez Avatar asked Feb 17 '26 07:02

Angel Martinez


2 Answers

I know it's an old one, but it's one I stumbled on today and with no approved answer, so I thought it could be of help to someone like me in the future.

Basically, the problem comes from using Date.now() instead of new Date(). My working example looks like this

  @Column({ type: "timestamptz", default: () => "CURRENT_TIMESTAMP" })
  createdDate: Date;

If the value is not provided, it will assign the current value. Note here that if you update a row and the new value misses the createdDate field, the old one will be overwritten.

Then if you want to set it manually, you simply use new Date() like this

const created = { ..., createdDate: new Date(), ...}
like image 192
Georgi Vatsov Avatar answered Feb 18 '26 19:02

Georgi Vatsov


You can use the @CreateDateColumn decorator to archieve what you want:

export class User {
  @CreateDateColumn()
  createdAt: Date;
}
like image 30
ejose19 Avatar answered Feb 18 '26 21:02

ejose19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!