js 日期对象 31 号 setMonth 的锅

BiaoChenXuYing

前言

需求:获取当前日期的前一个月份前端

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

1. 通常作法

当前日期若是不是 31 号, 是没问题的,是 31 号就会有问题:java

// 好比今天是 2018-09-30 号,前一个月应该是 2018-08-30 
let now = new Date(new Date("2018-09-30").setMonth(new Date("2018-09-30").getMonth() - 1))
console.log('now :', now.toLocaleString())
// now : 2018/8/30 上午8:00:00

// 好比今天是 2018-10-31 号,前一个月没有 31 号,因此结果 2018-10-01:
let now = new Date(new Date("2018-10-31").setMonth(new Date("2018-10-31").getMonth() - 1))
console.log('now :', now.toLocaleString())
// now : 2018/10/1 上午8:00:00
复制代码

2. 正确的方法:

2.1 方法一

原理: 当前时间减去当前时间的天数node

function initLastMonth(date) {
            let monthDate = new Date(date);
            let newDate = new Date(monthDate.getTime() - 24 * 60 * 60 * 1000 * monthDate.getDate())
            console.log('newDate :', newDate.toLocaleString())
          return newDate
}
initLastMonth("2018-10-31")
//  newDate : 2018/9/30 上午8:00:00
复制代码

2.2 方法二

原理: setMonth 以前先 setDate(1)react

function initLastMonth(date) {
            const now = new Date(date);
            now.setDate(1)
            now.setMonth(now.getMonth() - 1)
            console.log(now.toLocaleString()) 
            return now
        }
initLastMonth("2018-10-31")
// 2018/9/1 上午8:00:00
复制代码

最后

技术文章更新地址:githubgit

全栈开发 有兴趣的朋友能够扫下方二维码关注个人公众号,我会不按期更新有价值的内容。程序员

微信公众号:BiaoChenXuYing 分享 前端、后端开发等相关的技术文章,热点资源,全栈程序员的成长之路。github

关注公众号并回复 福利 便免费送你视频资源,绝对干货。后端

福利详情请点击: 免费资源分享--Python、Java、Linux、Go、node、vue、react、javaScriptbash

BiaoChenXuYing
相关文章
相关标签/搜索