Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js 日期对象 setMonth 的锅 #13

Open
biaochenxuying opened this issue Nov 1, 2018 · 0 comments
Open

js 日期对象 setMonth 的锅 #13

biaochenxuying opened this issue Nov 1, 2018 · 0 comments
Assignees
Labels
JavaScript JavaScript 相关知识点

Comments

@biaochenxuying
Copy link
Owner

biaochenxuying commented Nov 1, 2018

BiaoChenXuYing

前言

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

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

1. 一般做法

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

// 比如今天是 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 方法一

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


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)

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

最后

技术文章更新地址:github

@biaochenxuying biaochenxuying added the JavaScript JavaScript 相关知识点 label Nov 1, 2018
@biaochenxuying biaochenxuying self-assigned this Nov 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JavaScript 相关知识点
Projects
None yet
Development

No branches or pull requests

1 participant