getMonth 返回错误的 Values

编程入门 行业动态 更新时间:2024-10-04 15:25:50

getMonth 返回<a href=https://www.elefans.com/category/jswz/34/1771449.html style=错误的 Values"/>

getMonth 返回错误的 Values

我有这段代码,在mongoDB中搜索并获得所有的生日日期,并为每个生日日期从中提取月份,该代码完美地提取日期,但当我应用的问题 getMonth() 它返回错误的值

例如 today is 09/05/2020 当我申请 getMonth() 它返回 8 也不知道为什么

我使用的代码如下

User.find({}).lean(true).exec((err, users) => {
                let toBirth = [];


                for (let i =0 ; i < users.length; i++) { 
        const dt = datetime.create();
        dt.offsetInDays(0);
        const formatted = dt.format('m');
        const newFormatted = users[i].birthDay// the date here should be 09/05/2020
        const month = newFormatted.getMonth();
        console.log(month); // the output here is 8 it must be 5 and sometimes I get this error TypeError: Cannot read property 'getMonth' of undefined
           // console.log(formatted)
            if(month === formatted) {
                toBirth.push({user: users[i].userName, birthDay: users[i].birthDay});
            }
        }
           console.log(toBirth);
            });   
    } 

的形象 console.log(month) 低于

我得到的另一个错误如下

TypeError: Cannot read property 'getMonth' of undefined
回答如下:

根据注释 birthDay 是字符串。所以你需要基本上将其转换为Date。

最方便的解决方案是使用 momentjs 最受欢迎的日期时间库的许多英里。

const date = moment('09/05/2020', 'DD/MM/YYYY');
date.month()

注:月份是零索引,所以一月是0月份。

这里是 文档但你也可以像拆分字符串一样,使用第二个索引。birthDay.split('/')[1]

注:同样,要想得到当前月份的数据,你可以使用 const m = moment().month()

更多推荐

getMonth 返回错误的 Values

本文发布于:2024-05-13 12:36:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759545.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   getMonth   Values

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!