Adonis.js API return mismatch time as compared time in PostgreSQL DB?

35 views Asked by At

Im trying to retrieve data where date time is very important. But the time stored in DB is correct, but it mismatch when I called the API. The date and time stored in DB with data type "timestamptz"

Example of the issue :

IN DB -> 2024-02-25 18:00:00.000 +0800
API return -> 2024-02-25T10:00:00.000Z

The time in DB is 8 hours ahead than the API return, which the time in DB is the correct one.

I had checked the DB timezone, it's correct as my current location.

1

There are 1 answers

0
Marcus Neo On

I got the solution. Serialize it in the Adonis model.

And use timestamp data type in PostgreSQL, instead of timestamptz.

Moreover, remember to add "TZ=UTC" to your .env in Adonis

Example below :

  @column.dateTime({
    autoCreate: true,
    serialize: (value: DateTime | null) => {
      return value ? value.setZone('utc').toISO() : value
    },
  })
  public created_at: DateTime

  @column.dateTime({
    autoCreate: true,
    autoUpdate: true,
    serialize: (value: DateTime | null) => {
      return value ? value.setZone('utc').toISO() : value
    },
  })
  public updated_at: DateTime

Hope this help for anyone who got this issue.