代码:
function init() {
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth() + 1
if(month < 10) {
month = '0' + month
}
// let time = new Date(year, month, 1) // 效果一样 2022-08-31T16:00:00.000Z
let time = new Date(year, month) // 2022-08-31T16:00:00.000Z
let last_day = `${year}-${month}-${new Date(time.getTime() - 1000 * 60 * 60 * 24).getDate()}`
return { year, month, last_day }
}
console.log(`${init().year}-${init().month}-01`) // 第一天 2022-08-01
console.log(init().last_day) // 最后一天 2022-08-31
new Date(year, month) month可带0也可不带,效果一样
console.log(new Date(2022, 07)) //2022-07-31T16:00:00.000Z
console.log(new Date(2022, 7)) // 2022-07-31T16:00:00.000Z
console.log(new Date(2022, 2)) // 2022-02-28T16:00:00.000Z
console.log(new Date(22, 06)) // 1922-06-30T16:00:00.000Z
new Date( year, month, date, hrs, min, sec) 按给定的参数创建一日期对象
参数说明:
year的值为:需设定的年份-1900。例如需设定的年份是1997则year的值应为97,即1997-1900的结果。所以Date中可设定的年份最小为1900;