Is there an easy way to get Sequelize to return its date / time fields in a specific format?

We need to have sequel return dates in a specific format, not the default. As far as I can tell, there is no way to set this in options or in any other way. If you do not manually update the dates each time they are received, could anyone solve this problem easily? Or am I missing something?

+8
source share
4 answers

you can define your own instance methods getDate / setDate that will translate the date between the continuation of the internal view and the desired format, thus http://sequelize.readthedocs.org/en/latest/docs/models-definition/index.html (see Extension section models)

+7
source

You can use the Sequelize fn method. From the API Reference , the fn function will help you create an object that represents the SQL function in your query.

For instance:

 model.findAll({ attributes: [ 'id', [sequelize.fn('date_format', sequelize.col('date_col'), '%Y-%m-%d'), 'date_col_formed'] ]}) .then(function(result) { console.log(result); }); 

Will return data values:

 [ {"id": 1, "date_col_formed": "2014-01-01"}, {"id": 2, "date_col_formed": "2014-01-02"} // and so on... ] 
+28
source

In the case of the model we are creating with the Sequelize CLI, try something like this

  var sequelize= require('../models'); model.findAll({ attributes: [ 'id', 'title' [sequelize.Sequelize.fn('date_format', sequelize.Sequelize.col('col_name'), '%d %b %y'), 'col_name'] ]}.then(function(result)) { // dateformate=04 Nov 2017 console.log(result) } 

follow this link for formate

0
source

06/06/2019

A little late, but provided an update.

Sequelize is a powerful ORM (I'm not saying this is the best solution), but it has very poor documentation.

In any case, if you want this to be configured in your models, besides the need to repeat it according to your requests, as other answers indicate what you could do:

  const Test = sequelize.define('test', { // attributes name: { type: DataType.STRING, allowNull: false }, createdAt: { type: DataType.DATE, //note here this is the guy that you are looking for get() { return moment(this.getDataValue('createdAt')).format('DD/MM/YYYY h:mm:ss'); } }, updatedAt: { type: DataType.DATE, get() { return moment(this.getDataValue('updatedAt')).format('DD/MM/YYYY h:mm:ss'); } } 

If you use dates to provide information in the form: last update, first login, last login. This is the way.

The get function returns a new formatted element, so it cannot be limited by dates! Just remember that this will slow down your request, so use it carefully. ;)

more information (I know that I know, but docs is the name of the game): http://docs.sequelizejs.com/manual/models-definition.html#getters--amp--setters

0
source

Source: https://habr.com/ru/post/946221/


All Articles