Skip to content

DateUtils.mixedDateToDateString should support UTC #11515

Open
@dgildeh

Description

@dgildeh

Feature Description

I spent a while over the weekend trying to find out why my dates were being converted from UTC strings using the column transformer in my queries before I realized the SQLIte Abstract Driver I was using was doing something funky behind the scenes because my column type was 'date'.

The function that converts the date to write to the database converts it to a local-time string:

https://github.com/typeorm/typeorm/blob/930eefd758eb6954f29dc8b8c4f189eb02491ffd/src/util/DateUtils.ts#L28C12-L28C33

It would be great to add utc: boolean option to date fields and if set to true, use UTC string instead of the local time string so the database can save values in a consistent timezone.

The Solution

Modify the date type column to allow a property utc: boolean.

If set to true, ensure this function DateUtils.mixedDateToDateString handles UTC conversion instead of just local time.

Considered Alternatives

In the meantime you can set your column type to 'text' and write a custom transformer like below:

  @Column({
    type: 'text',
    default: () => "(date('now', 'utc'))",
    transformer: {
      to: (value: Date) => {
        return value ? value.toISOString().slice(0, 10) : undefined
      },
      from: (value: string | Date) => {
        if (value instanceof Date) {
          return new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate()))
        }
        const [year, month, day] = value.split('-').map(Number)
        return new Date(Date.UTC(year, month - 1, day))
      },
    },
  })
  date!: Date

Additional Context

No response

Relevant Database Driver(s)

  • aurora-mysql
  • aurora-postgres
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • spanner
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting PRsbugnew featuresize-sSimple tasks that require minimal effort. Estimated effort: 1-2 hours.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions