Drizzle ORM date conversion problem between Javascript and PostgreSQL? – Postgresql

by
Alexei Petrov
angular-forms drizzle postgresql timezone utc

Quick Fix: In the Drizzle ORM definition, set the mode attribute of the date column to "date" like date: date("date", {mode: "date"}).notNull(). This will ensure that the date values are correctly converted between JavaScript and PostgreSQL.

The Problem:

A user is experiencing an inconsistency in date handling between Javascript and PostgreSQL using the Drizzle ORM. When retrieving a date value from the database, the Javascript code shows a different date compared to what is displayed in the database’s Studio. Additionally, comparing dates in a subsequent query leads to incorrect results, indicating a mismatch in date interpretation. The user wants to resolve this issue and ensure accurate date handling in their application.

The Solutions:

Solution 1: Change the date column’s definition

To resolve the issue of date conversion between JavaScript and PostgreSQL, it is recommended to modify the definition of the date column in the drizzle model to:

date: date("date", {mode: "date"}).notNull(),

By adding the mode option as “date”, it specifies that the column should store only the date part of the timestamp, excluding the time component. This ensures that the date values are represented consistently in both JavaScript and PostgreSQL, preventing any timezone-related discrepancies.

This modification ensures that the date values are stored in the database as pure dates, without any time component. As a result, when you query the database or compare dates in JavaScript, you will get consistent results, regardless of your timezone or the timezone settings of the database.

Q&A

How can I solve the date conversion problem between ↓ and PostrgreSQL using DrizzleORM

Change the date column’s definition to include mode: "date"

Why does the date of a Drizzle orm model differ from the one in the database

Most likely the date column is defined without the mode setting "date"

What is the mode setting in Drizzle that sets the date correctly

mode:"date"

Video Explanation:

The following video, titled "Drizzle ORM #2- SQL Types - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Please Support me by subscribing to my channel https://www.youtube.com/@sakuradev?sub_confirmation=1 In this episode we delve into data ...