sequelize查询数据的日期格式化

首先确定时区

const sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: 'mssql',
  dialectOptions: {
    instanceName: 'SQLEXPRESS'
  },
  // define: {
  //   schema: "core"
  // },
  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
  timezone: '+08:00' //东八时区
});

其次引入日期处理类库 Moment.js

npm install moment --save

或者直接访问http://momentjs.cn/,查看你需要的安装方式

再次定义引用

var moment = require('moment');
const Device = sequelize.define('DeviceDetail',
  {
    DeviceNo: {
      type: Sequelize.INTEGER
    },

    ServiceTime: {
      type: Sequelize.DATE,
      get() {
        return moment(this.getDataValue('ServiceTime')).format('YYYY-MM-DD HH:mm:ss');
      }
    }
  }, {
    tableName: 'DeviceDetail',
    timestamps: false,
    freezeTableName: true
  });

输出的格式即YYYY-MM-DD HH:mm:ss

出现问题:查询返回的时间会比数据库里存储的时间多八个小时,因为数据库的时间使用entityframework保存的,而不是用sequelize保存的,所以这样修改一下,就可以保证查询返回本地的时间和数据库时间一致了

moment(this.getDataValue('ServiceTime')).utcOffset(0).format('YYYY-MM-DD HH:mm:ss')
原文地址:https://www.cnblogs.com/smartsensor/p/8057989.html