Sequelize转换成秒后减去updatedAt和createdAt

Sequelize subtract updatedAt and createdAt after converted into seconds

嘿,我真的是 SEQUELIZE 的新手,对于这个项目,我试图在转换成秒后扣除 updatedAtcreatedAt 值。

更新和创建时间列采用 DATETIME 格式。其中一行包含 2021-03-03 21:30:58 的 createdAt 值和 2021-03-03 22:42:05 的 updatedAt 值。有没有一种方法可以先将该值转换为秒数,然后再减去它。我在下面尝试过,但它没有格式化为秒,而且 timePlayed 始终将结果显示为 14000。

任何人都可以让我知道我想在 sequelize 上做什么以将日期格式化为秒然后减去 createdAtupdatedAt 之间的值吗?

router.get(
    "/sessions/average_team_time",
    (req, res) => {
      models.Session.findAll({
        createdAt: sequelize.literal('createdAt * 100000'),
        updatedAt: sequelize.literal('updatedAt * 100000')
        'attributes': [
              'id',
              'createdAt',
              'updatedAt',
              [Sequelize.fn('time', Sequelize.col('updatedAt')), 'updatedAtHour'],
              [Sequelize.fn('date_format', Sequelize.col('createdAt'), '%Y-%m-%d %H:%m:%S'), 'date_formed'],
              [Sequelize.literal('(updatedAt - createdAt)'), 'timePlayed']
         ]
      })
        .then((sessions) => {
          res.json(sessions);
        })
        .catch((err) => res.json(err));
    }
  ); 
db.Session.findAll({
    attributes: [
        'id',
        'createdAt',
        'updatedAt',
        [Sequelize.fn('TIMESTAMPDIFF', Sequelize.literal('SECOND'), Sequelize.col("createdAt"), Sequelize.col("updatedAt")), 'timePlayed']

    ]
})
    .then(resp => res.send(resp))
    .catch(error => res.send({ status: false, error: error }))

有时候,javascript比sequelzie

更强大
db.Session.findAll({
    // createdAt: sequelize.literal('createdAt * 100000'),
    // updatedAt: sequelize.literal('updatedAt * 100000'),
    attributes: [
        'id',
        'createdAt',
        'updatedAt',
        [Sequelize.fn('time', Sequelize.col('updatedAt')), 'updatedAtHour'],
        [Sequelize.fn('date_format', Sequelize.col('createdAt'), '%Y-%m-%d %H:%m:%S'), 'date_formed'],
        // [Sequelize.literal('(updatedAt - createdAt)'), 'timePlayed']
    ]
})
    .then((sessions) => {
        sessions = JSON.parse(JSON.stringify(sessions))
        sessions = sessions || []
        sessions = sessions.map(item => {
            item.timePlayed = new Date(item.updatedAt).getTime() - new Date(item.createdAt).getTime()
            return item;
        })
        res.json(sessions);
    })
    .catch((err) => res.json(err));

或者,我们可以使用DataTypes.VIRTUAL

模型:定义

Session.init({
    timePlayed: {
        type: DataTypes.VIRTUAL,
        get() {
            return new Date(this.updatedAt).getTime() - new Date(this.createdAt).getTime()
        }
    }
})

...

db.Session.findAll({
    attributes: ['id', 'createdAt', 'updatedAt', 'timePlayed']
})
    .then(resp => res.send(resp))
    .catch(error => res.send({ status: false, error: error }))