How to format the date for date types values using Sequelize

Customizing Sequelize date format with Sequelize.fn()

Thesequelize.fn()method is used to call a native database function to modify the way your query worksFor example, you can call the UPPER() function of MySQL and apply it to a column that you have as follows:

The sequelize.fn() method is used to call a native database function to modify the way your query works.

Model.findAll({
  attributes: {
    include: [
      [ sequelize.fn("UPPER", sequelize.col("username")), 'username_upper' ]
    ],
  },
});

The sequelize.fn() method must be enclosed in an array using the following format:

sequelize.fn(
  "function to call", 
  "first parameter", 
  "second parameter (if any)",
  "and the next parameter..."
)
, "the column alias"

The fn() method can only be called from the attributes or attributes.include property, and the properties are only supported by the findAll() method.

For example

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());
The output of the above console.log() call would be as follows:
{
  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 *