Search code examples
node.jssql-servertypeormtimezone-offsetdate-fns

Node.js with TypeORM inserts wrong timezones into Azure SQL Database


I have a backend written on top of node.js, I'm using TypeORM as the ORM and Azure SQL Database to store my data. When I call the ORM's create() and save() functions, I'm passing in the correct date and time as can be seen below. But when I query the inserted data in the server, the timezone has shifted from -03:00 to +00:00. It maybe a normal behavior, since I'm new working with dates though.

This is the code where I call the create() in:

class CreateAppointmentsService {
  public async execute({ provider, date }: RequestDTO): Promise<Appointment> {
    const appointmentsRepository = getCustomRepository(AppointmentsRepository);
    const roundDate = startOfHour(date);
    const foundAppointment = await appointmentsRepository.findByDate(roundDate);
    if (foundAppointment) {
      throw Error('This date and time already has a booking.');
    }
    const appointment = appointmentsRepository.create({
      provider,
      date: roundDate,
    });
    await appointmentsRepository.save(appointment);
    return appointment;
  }
}

This is my debug information, showing date and time in expected timezone.

This is the data in the database. The field type is datetimeoffset and the server time is set to UTC (+00:00).

Thanks in advance! =)

[EDIT]: Explaining better: the time I posted to the database is rounded to 20:00 -03:00 (America/Sao_Paulo/Brasilia). If you look the column "created_at", the time is updated to UTC, but the column "data" only got the timezone set to +00:00, the time remais 20:00.


Solution

  • Found the problem! I forgot to set the "date" column to datetimeoffset in the typeORM model =(.

    How it was:

      @Column()
      date: Date;
    

    Changed to:

      @Column('datetimeoffset')
      date: Date;
    

    Now it work wonders! The correct timezone is being set alongside the time. Cheers!