Sequelize Where statement with date

前端 未结 4 1909
野的像风
野的像风 2020-12-14 14:01

I am using sequelize as my backend ORM. Now i wish to do some where operations on a Date.

More Speceficly i want to get all data where a date is from now and 7 days

4条回答
  •  隐瞒了意图╮
    2020-12-14 14:31

    This solution is without the moment.js library.

    Between 7 days ago and now

    const sevenDaysAgo = new Date(new Date().setDate(new Date().getDate() - 7));
    models.instagram.findAll({
      where: {
        my_date: {
          $gt: sevenDaysAgo,
          $lt: new Date(),
        },
      },
    });
    

    Between now and 7 from now

    const sevenDaysFromNow = new Date(new Date().setDate(new Date().getDate() + 7));
    models.instagram.findAll({
      where: {
        my_date: {
          $gt: new Date(),
          $lt: sevenDaysFromNow,
        },
      },
    });
    

    Notes:

    • $gt stands for "greater than". You could use $gte instead of $gt. $gte stands for "greater than or equal to". Same for $lte of course.
    • Technically speaking, you need both $lt and $gt to make sure that the date isn't into the future (per the original question).
    • Other answers show the use of [Sequelize.Op.gt] instead of $gt. Use that if on Sequelize v5.

提交回复
热议问题