【问题标题】:Comparing date in node js using sequelize使用sequelize比较节点js中的日期
【发布时间】:2020-08-14 10:32:49
【问题描述】:

实际上我正在使用 sqlite 数据库(表)。 Node.js 用于后端。 现在我需要获取属于两个特定日期的记录。(例如 24.04.2020 11.00 AM 到 28.04.2020 02.00 pm) 我该怎么做?我需要以什么格式将日期和时间存储在数据库中?以及我如何比较?

【问题讨论】:

  • 你可以使用像 sqlite3 这样的包,然后使用这个reference 来创建正确的查询
  • 时间对我来说也很重要。例如 24.04.2020 11.00 AM 到 28.04.2020 02.00 pm
  • 然后就可以使用时间戳了。查看reference也探索moment.js来在js中操作时间。

标签: node.js sqlite sequelize.js


【解决方案1】:

Sequelize 使用 js 日期。所以你可以做类似的事情:

const { Op } = require("sequelize");

Foo.findAll({
  where: {

    // myDateColumn < [timestamp] AND myDateColumn > [timestamp]
    {
      myDateColumn: {
        [Op.lt]: new Date(),
        [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
      }
    },


    // myDateColumn in range
    [Op.notBetween]: [new Date(), new Date(new Date() - 24 * 60 * 60 * 1000)]
  }
});

我还建议使用 moment.js 或 luxon(个人最喜欢的)来处理日期。

使用 luxon 格式化日期:

const DateTime = require('luxon');

// the reason we love luxon is because it's easy to set the timezone 
const startDate = DateTime.local().setZone('America/New_York').fromISO('2020-04-24T11:00:00').toJSDate();

在这里阅读更多:https://sequelize.org/master/manual/model-querying-basics.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 2018-04-24
    • 2019-04-24
    • 2021-08-17
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多