首先確定時區
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')