我正在尝试比较来自后端的月份号字段month=6
的值与当前月份号。如果匹配正确,则“做某事”,否则做“其他事情”。
我尝试使用javascript Date()对象以及moment():
var date = new Date();
var month = date.getMonth()+1;
时刻:
var month = moment().month("M");
这是需要当前月份值的函数
// get all Item usage on each item by month
const GroupedByMonth = Object.values(
data.reduce((acc, curr) => {
if (curr._id.month === month){
return (
(acc[curr._id.name] = {
month: curr._id.month,
name: curr._id.name,
totalAmountSold:
(acc[curr._id.name]?.totalAmountSold || 0) +
curr.totalAmountSold,
}),
acc
);
}
return acc;
}, {})
);
console.log(GroupedByMonth);
来自后端的对象:
{month: 6, name: "Cement", totalAmountSold: -17}
预期输出应为:
if (curr._id.month(6 coming from backend) === month(6 coming from date object){
in the case of true, the rest of the functions is performed
Non of the method i tried worked as expected. I need help in solving this problem
答案 0 :(得分:2)
我不太了解您的意思
我尝试的方法都无法按预期工作。
到目前为止,您尝试了什么?结果如何?
除此之外,您还可以尝试以下操作:
var today = new Date(); //Thu Jun 18 2020 10:17:04 GMT-0300
var month = ('0' + (today.getMonth() + 1)).slice(-2);
//Expected output of month: '06'
由于您使用的是===
,请确保您要比较的值和类型都匹配
答案 1 :(得分:1)
function isDateMatched (monthNo) {
return new Date().getMonth() === monthNo;
}
console.log('5th month ', isDateMatched(5))
console.log('4th month ', isDateMatched(4))
参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
Date.getMonth()
返回当前月份。
您可以简单地传递month否从后端获取并将其传递给isDateMatched
函数,它将返回一个布尔值,即true / false
基于此结果,您可以完成工作。