We need to have sequelize return dates in a particular format, not the default one. As far as I can tell, there is no way to set that up in options, or any other way. Short of manually updating the dates every time after they are retrieved, anyone been able to solve this easily? Or am I missing something?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
you can define custom instance methods getDate/setDate which would translate date between sequelize internal representation and desired format like so http://sequelize.readthedocs.org/en/latest/docs/models-definition/index.html (see 'Expansion of models' section)
回答2:
You can, use the Sequelize fn
method. From the API Reference, the fn
function will help create an object representing a SQL function in your query.
For example:
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... ]
回答3:
In case of Model that we create using 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) }