You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Sequelize查询匹配当前年月的start_date数据?

查询Sequelize模型中当前年月的数据

嘿,这事儿很简单,咱们只需要先确定当前年月的时间范围,再用Sequelize的查询条件筛选出这个范围内的数据就行。下面是具体的实现步骤:

1. 准备时间范围

首先得算出当前月份的起始和结束时间:

  • 起始时间:当月第一天的00:00:00
  • 结束时间:当月最后一天的23:59:59.999

对应的代码如下:

// 获取当前年份和月份(注意:JS的月份是0-based,0代表1月,11代表12月)
const currentYear = new Date().getFullYear();
const currentMonth = new Date().getMonth();

// 当月第一天的00:00:00
const startOfMonth = new Date(currentYear, currentMonth, 1);
// 下月第一天减1毫秒,得到当月最后一天的23:59:59.999
const endOfMonth = new Date(currentYear, currentMonth + 1, 1);
endOfMonth.setMilliseconds(endOfMonth.getMilliseconds() - 1);

2. 编写Sequelize查询语句

接下来就可以用这个时间范围作为查询条件,从Test模型中筛选数据了。记得要引入Sequelize的操作符Op:

const { Op } = require('sequelize');
const Test = require('./path-to-your-test-model'); // 替换成你的Test模型路径

Test.findAll({
  where: {
    start_date: {
      // 用gte(大于等于)和lte(小于等于)限定时间范围
      [Op.gte]: startOfMonth,
      [Op.lte]: endOfMonth
    }
  }
})
.then(matchingRecords => {
  console.log('符合当前年月的数据:', matchingRecords);
})
.catch(error => {
  console.error('查询失败:', error);
});

你也可以用Op.between来简化条件写法,效果是完全一样的:

start_date: {
  [Op.between]: [startOfMonth, endOfMonth]
}

这样执行查询后,就能精准获取到start_date属于当前年月的记录(也就是你例子里的2018-05-05和2018-05-06啦)。

内容的提问来源于stack exchange,提问作者Mrugesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:09:08