日常开发记录-js 获取当前月份的第一天和最后一天

代码:

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值