随笔 - 142  文章 - 14  评论 - 0  阅读 - 70351

日常开发记录-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;

posted on   法老的微笑  阅读(757)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示