javascript - 如何从日期对象中获取当前月份数
问题描述
我正在尝试将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
解决方案
我不太明白你的意思
我尝试的方法都没有按预期工作。
你试过什么了?结果如何?
除此之外,您可以尝试这样的事情:
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'
确保您尝试比较的内容在值和类型上匹配,因为您正在使用===
推荐阅读
- c# - 集成身份服务器;Docker 和 MVC 核心(Web 客户端)
- ios - CAEmitterLayer 没有用 CACurrentMediaTime() 正确计时,有时根本不显示
- angular - 有条件地交换元素在一行中的位置
- javascript - 有没有办法给咖喱箭头函数一个类型/标签?
- r - 如何在R中绘制下图?这些类型的图表叫什么?
- web - 如何使用我网站上的链接打开应用程序?
- swift - BLE 在蓝牙设备附近执行功能
- python - 如何创建一副牌,将它们“洗牌”,然后让两名玩家挑选最上面的两张牌
- azure - 无法使用 Power BI 从 Azure DataLake 的源导入数据:错误消息“无法将修改保存到服务器”
- android-studio - 未找到 Android Studio 上的 GridLayout