node.js 有没有一种简单的方法可以让 Sequelize 以特定格式返回它的日期/时间字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16847672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:40:27  来源:igfitidea点击:

Is there a simple way to make Sequelize return it's date/time fields in a particular format?

node.jssequelize.js

提问by CargoMeister

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?

我们需要以特定格式而不是默认格式对返回日期进行续集。据我所知,无法在选项或任何其他方式中进行设置。每次检索后都没有手动更新日期,有人能够轻松解决这个问题吗?或者我错过了什么?

采纳答案by mrvn

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)

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

回答by Jon Saw

You can, use the Sequelize fnmethod. From the API Reference, the fnfunction will help create an object representing a SQL function in your query.

您可以使用 Sequelizefn方法。从API 参考 中,该fn函数将帮助创建一个表示查询中的 SQL 函数的对象。

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...
]

回答by iwaduarte

21/06/2019

21/06/2019

A little bit late but providing an update.

有点晚,但提供更新。

Sequelize is a powerful ORM (I am not saying is the best solution out there) but has a very bad documentation.

Sequelize 是一个强大的 ORM(我不是说它是最好的解决方案),但它的文档非常糟糕。

Anyway if you want to have this configured in your models one way apart from having to repeat this across your queries as other responses state you could be doing:

无论如何,如果你想在你的模型中配置这个,除了必须在你的查询中重复这个之外,因为其他响应状态你可以这样做:

     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 are using dates to provide info as: last updated, first login, last login. This is the way to go.

如果您使用日期提供信息为:上次更新、首次登录、上次登录。这是要走的路。

The function get returns the new formatted element so it should not be restricted to dates either! Just bear in mind that this will slow your query so use cautiously. ;)

函数 get 返回新的格式化元素,因此它也不应该仅限于日期!请记住,这会减慢您的查询速度,因此请谨慎使用。;)

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

更多信息(我知道我知道,但 docs 是游戏的名称):http: //docs.sequelizejs.com/manual/models-definition.html#getters--amp--setters

回答by Adiii

In case of Model that we create using Sequelize CLI try something like this

对于我们使用 Sequelize CLI 创建的模型,请尝试这样的操作

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

visit this link for formate

访问此链接了解甲酸