Search code examples
node.jssql-servertypeorm

TypeORM inserts dates incorrectly - using Microsoft SQL Server


I have a weird problem with TypeORM (v0.2.45) using Microsoft SQL Server (mssql v6.3.1)

I have an Entity which has columns of type date which when inserting data a day is subtracted from the date for example:

@Entity("employees")
export class Employees extends BaseEntity {
    @PrimaryGeneratedColumn("uuid")
    uuid: string;

    @Column({type: 'date'})
    birth_date: Date;

    @Column({type: 'date'})
    entry_date: Date;
}

I insert 2022-03-15 (YYYY-MM-DD) and the record is saved in the table as 2022-03-14

It should be noted that I have already carried out the corresponding tests to verify that the date did not mutate before inserting and ultimately the problem comes from the mssql dependency.

Investigating I discovered that there is a problem as described here:

TypeORM inserts dates incorrectly

It has worked for me to change the type to datetimeoffset as described below:

@Entity("employees")
export class Employees extends BaseEntity {
    @PrimaryGeneratedColumn("uuid")
    uuid: string;

    @Column({type: 'datetimeoffset'})
    birth_date: Date;

    @Column({type: 'datetimeoffset'})
    entry_date: Date;
}

The detail that I have is that when performing the corresponding migrations, the data type of the column will change to datetimeoffset and I consider that it is not a good practice. The other option that seems very vague to me is to add that day that is subtracted from the date before inserting it But both solutions I consider that they are not the most optimal.

I already updated the TypeORM and MSSQL dependencies and the problem persists How could I solve it? Any ideas?


Solution

  • createBuzonDto.desde = new Date(createBuzonDto.desde.getUTCFullYear(), createBuzonDto.desde.getUTCMonth(), createBuzonDto.desde.getUTCDate())