Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create columns with type Date and type DateTime in nestjs with typeORM?

I am new with nestjs. How can I set columns that accepts Date format and dateTime format?

Not in both cases, the columns are two differents column, one accept Date and other dateTime.

like image 970
kri-dev Avatar asked Jul 02 '20 12:07

kri-dev


3 Answers

You can see the docs here that explains the @Column decorator. In @Column there is an option called type -> here is where you specify which type of date you want to store for that specific column.

More on column types here.

For example (using 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;

Note that date_only is of type string. See this issue for more information.

Moreover, automatic dates for certain events are possible: 

  • Creation Date, available via @CreateDateColumn() decorator.
  • Last Updated Date, available via @UpdateDateColumn() decorator.
  • Deletion Date, only when soft delete is enabled, available via @DeleteDateColumn() decorator.
@CreateDateColumn()
created_at: Date; // Creation date

@UpdateDateColumn()
updated_at: Date; // Last updated date

@DeleteDateColumn()
deleted_at: Date; // Deletion date
like image 115
Carlo Corradini Avatar answered Nov 11 '22 19:11

Carlo Corradini


How about ?

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

EDIT

You can find more info here

like image 38
Luis Contreras Avatar answered Nov 11 '22 19:11

Luis Contreras


To add more to this ticket as DateTime was not even mentioned:

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

  /**
   * End DateTime
   */
  @Column({
    type: 'datetime',
    nullable: true,
  })
  @Index()
  end: string;

This is for those not wanting or needing to use

@CreateDateColumn()

@UpdateDateColumn()

like image 6
Jeremy Avatar answered Nov 11 '22 20:11

Jeremy