错误的 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
发布评论