Formatting Dates in Sequelize

When working with Sequelize (the Node.js ORM), handling date/time fields in a readable or custom format is a common requirement. By default, Sequelize returns dates in ISO formats.

However, many applications require alternative formats such as DD-MM-YYYY HH:mm:ss, localized date strings, or more human-readable representations.

How Sequelize Handles Dates Out of the Box

Sequelize offers two main data types for storing dates: • DATEONLY: corresponds to SQL’s DATE (no time component) • DATE: corresponds to SQL’s DATETIME / TIMESTAMP (has both date and time) Let’s look at an example: const Invoice = sequelize.define(“Invoice”, { invoiceDate: { type: Sequelize.DATEONLY, }, paymentDate: { type: Sequelize.DATE, }, amount: { type: Sequelize.INTEGER, }, }, { timestamps: false, }); Suppose the database row is: idinvoiceDatepaymentDateamount12022-01-172022-01-17 04:33:12300 If you fetch that row via: const invoice = await Invoice.findByPk(1); console.log(invoice.toJSON()); You’ll see something like: { “id”: 1, “invoiceDate”: “2022-01-17”, “paymentDate”: “2022-01-17T04:33:12.000Z”, “amount”: 300 } • invoiceDate (type DATEONLY) is returned as a string in ISO YYYY-MM-DD format. • paymentDate (type DATE) is a JavaScript Date object, serialized in ISO 8601 format. Method 1: Use sequelize.fn() with Database Formatting Functions You can leverage your database’s native date formatting functions (like DATE_FORMAT in MySQL or TO_CHAR in PostgreSQL) via Sequelize’s fn() helper. This approach asks the database to return a formatted string directly. Example (MySQL) const invoices = await Invoice.findAll({ attributes: { include: [ “id”, “invoiceDate”, [ sequelize.fn( “DATE_FORMAT”, sequelize.col(“paymentDate”), “%d-%m-%Y %H:%i:%s” ), “paymentDate” ], “amount” ], }, }); console.log(invoices[0].toJSON()); Output: { “id”: 1, “invoiceDate”: “2022-01-17”, “paymentDate”: “17-01-2022 04:33:12”, “amount”: 300 }

Method 2: Use a Getter (get()) on the Model Attribute (JavaScript Formatting) A more flexible method is defining a custom getter on your model attribute. The idea is: fetch the raw Date object, then format it in JavaScript using toLocaleString() or a date library. Example const Invoice = sequelize.define(“Invoice”, { invoiceDate: { type: Sequelize.DATEONLY, }, paymentDate: { type: Sequelize.DATE, get() { const raw = this.getDataValue(“paymentDate”); if (!raw) return null; return raw.toLocaleString(“en-GB”, { timeZone: “UTC” }); } }, amount: { type: Sequelize.INTEGER, }, }, { timestamps: false, }); Fetch and log: const invoice = await Invoice.findByPk(1); console.log(invoice.toJSON()); Output: { “id”: 1, “invoiceDate”: “2022-01-17”, “paymentDate”: “17/01/2022, 04:33:12”, “amount”: 300 }

Leave a comment

Your email address will not be published. Required fields are marked *