Handling Timezone Issues in MySQL with Sequelize: Custom Getters for DATE Columns
This article explains how MySQL stores dates in UTC, why Sequelize returns UTC values despite a configured timezone, and demonstrates using custom getter methods (with moment) to automatically format DATE fields, including an advanced approach to apply the getter across multiple models.
The article is based on MySQL and Sequelize and starts by describing the common frustration with handling time‑type data because MySQL stores timestamps in UTC, which appears eight hours behind the China Standard Time zone.
Sequelize, a relational‑database ORM similar to Mongoose for MongoDB, is introduced and its three main parts are outlined: (1) macro configuration (database name, credentials, host, pool, etc.), (2) model definitions that map tables, and (3) column definitions referred to as schemas.
Even after setting the timezone to UTC+8 in the configuration, queries still return UTC dates because both MySQL and Sequelize transform DATE types; the timezone setting only affects how data is written, not read.
The solution is to define custom get (and optionally set ) methods for DATE columns in the model, using the moment library to convert the stored UTC value to the desired local format.
For projects with many tables and DATE columns, repeatedly adding the same getter is cumbersome. An advanced technique is presented: copy the existing column definitions, iterate over each table’s columns, detect DATE types, and inject a unified getter that formats dates (defaulting to YYYY-MM-DD HH:mm:ss ) while allowing custom formats when needed.
The article concludes that the described approach resolves the timezone display issue in a clean and reusable way.
System Architect Go
Programming, architecture, application development, message queues, middleware, databases, containerization, big data, image processing, machine learning, AI, personal growth.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.