Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM not converting `Date` to utc

Lets start by providing the database definition of the entity in question:

    @Column({ name: "last_seen", type: "timestamp", nullable: true })
    @Index()
    public lastSeen: Date | null = null;

    @CreateDateColumn({ name: "created", type: "timestamp", nullable: false })
    public created!: Date;

The database is UTC but the server (in development) is in the "Asia/Tehran" time zone. As far as I know, TypeORM should store dates in UTC and convert them back to local time on retrieval.

However, and I think this is happening recently since I don't remember having a similar issue on this project which is ongoing for 6 months now, but the Dates are now stored raw. For example, if I save 10:00+4:30 in javascript for the lastSeen property it will be saved invalidly as 10:00.

On the other hand, when reading dates that are created by the database in "UTC" automatically, for example as is the case for the created property, the value is read in the local timezone instead of getting converted from "UTC". In these cases, the data is stored correctly in the Database in "UTC".

Is there an option that I am missing here in regard to date time conversion with TypeORM?

like image 610
Soroush Falahati Avatar asked Sep 08 '25 05:09

Soroush Falahati


1 Answers

Use timestamptz (timestamp with timezone) instead of the basic timestamp.

See this article for more information.

like image 163
Carlo Corradini Avatar answered Sep 11 '25 02:09

Carlo Corradini