如何解决如何使用javascript从mysql获取当前月份数据?
我有一个记录表,只需要获取当前月份的记录即可。
代码:
let startDate = req.body.startDate
let endDate = req.body.endDate
let result = await caseRegistration.findByDate({ pathology_id : req.body.pathology_id,created_at: {
'>=': new Date(startDate),'<=': new Date(endDate)
}
})
以上代码我正在传递特定日期以获取记录。但是我的要求是,如果请求没有任何日期,那么我只想获取当前月份的数据。你能帮我吗?
解决方法
var date = new Date();
var firstDay = new Date(date.getFullYear(),date.getMonth(),1);
var lastDay = new Date(date.getFullYear(),daysInMonth(date.getMonth()+1,date.getFullYear()));
firstDay=>Tue Sep 01 2020 00:00:00 GMT+0530 (India Standard Time)
lastDay=> Wed Sep 30 2020 00:00:00 GMT+0530 (India Standard Time)
请注意您想要的时区和日期格式(可能是任意值)
,如果startDate和endDate为空,则使用以下方法查找本月的第一个日期和最后一个日期:
var date = new Date();
var firstDateOfCurrentMonth = new Date(date.getFullYear(),1);
var endDateOfCurrentMonth = new Date(date.getFullYear(),date.getMonth() + 1,0);
现在您可以将这些日期分配给startDate和endDate
statDate=firstDateOfCurrentMonth;
endDate=endDateOfCurrentMonth;