JS日期对象当月有31天setMonth问题

当我们使用日期对象的时候,或多或少需要操作的月份,一般直接用setMonth来实现的,可是,当月份天数小于31天的时候,这样子的代码实现是没问题的,

        //例一
        const now = new Date();
        console.log(now) //Wed May 30 2018 11:28:40 GMT+0800 (中国标准时间)
        now.setMonth(now.getMonth()-1)
        console.log(now) //Mon Apr 30 2018 11:28:40 GMT+0800 (中国标准时间)

当月份有31天,问题就来了,比如说我要获取到当前月份的上个月,切好当前月的今天是31号,那我获取到的还是当前月,只不过变成1号,那怎么解决问题呢,可以在setMonth之前先setDate(1)就可以,

       //例二
        const now = new Date();
        console.log(now) //Thu May 31 2018 11:26:33 GMT+0800 (中国标准时间)
        now.setMonth(now.getMonth()-1)
        console.log(now)//Tue May 01 2018 11:26:33 GMT+0800 (中国标准时间)

        //例三 解决方案
        const now = new Date();
        console.log(now) //Thu May 31 2018 11:43:08 GMT+0800 (中国标准时间)
        now.setDate(1)
        now.setMonth(now.getMonth()-1)
        console.log(now) //Sun Apr 01 2018 11:43:08 GMT+0800 (中国标准时间)

附:

  • 对象的month是从0开始的,即0为一月份
  • new Date()是获取系统时间而不是互联网时间

你可能感兴趣的:(JS日期对象当月有31天setMonth问题)