有没有简单的方法来使Sequelize返回特定格式的date/时间字段?

我们需要以特定的格式重新设置返回date,而不是默认的date。 据我所知,没有办法以select或其他方式来设置。 每次检索后都没有手动更新date,任何人都可以很容易地解决这个问题? 还是我错过了什么?

你可以定义自定义的实例方法getDate / setDate,它可以在sequelize内部表示和期望的格式之间转换date,如http://sequelize.readthedocs.org/en/latest/docs/models-definition/index.html (见“扩展模型“部分)

你可以使用Sequelize fn方法。 从API参考中 , fn函数将帮助在查询中创build表示SQL函数的对象。

例如:

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

将返回数据值:

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

在我们使用Sequelize CLI创build的模型的情况下,尝试这样的事情

  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) } 

请访问此链接formate