首页 > 解决方案 > 如何从日期对象中获取当前月份数

问题描述

我正在尝试将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

标签: javascriptreactjs

解决方案


我不太明白你的意思

我尝试的方法都没有按预期工作。

你试过什么了?结果如何?

除此之外,您可以尝试这样的事情:

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'

确保您尝试比较的内容在值和类型上匹配,因为您正在使用===


推荐阅读