从新日期(日期)获取日期/月份,获取当前日期/月份

时间:2019-10-21 14:31:12

标签: javascript

我在使用新的Date构造函数时遇到问题

当我设置新的Date(date)并要求控制台进行打印时,它会返回我想要的日期,但是如果我尝试获取日期/月份,它将返回我的当前日期/月份,就像我设置为{{ 1}}

new Date().getDay()

我希望输出为31,但它不起作用,我做错了什么吗?

3 个答案:

答案 0 :(得分:1)

如果要打印日期(1-31),则必须使用getDate()方法。

let date, end;

date = new Date()
end = new Date(date.getFullYear(), date.getMonth() + 1, 0)

console.log(end) // prints: Thu Oct 31 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
console.log(end.getDate()) // prints: 31

答案 1 :(得分:1)

我认为您使用的方法错误

let end = new Date(date.getFullYear(), date.getMonth() + 1, 0)

console.log(end) // prints: Thu Oct 31 2019 00:00:00 GMT-0300 (Horário Padrão de Brasília)
console.log(end.getDay()) // Returns the day of the week
console.log(end.getDate()) // Returns the day of the month

答案 2 :(得分:0)

getDay()不返回月份中的天数。它返回星期几。

使用getDate()获得期望的回报。您也可以在here

中检查文档