js 日期对象 31 号 setMonth 的锅
生活随笔
收集整理的這篇文章主要介紹了
js 日期对象 31 号 setMonth 的锅
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言
需求:獲取當(dāng)前日期的前一個月份
當(dāng)月有 31 天時,JS 日期對象 setMonth 問題
1. 一般做法
當(dāng)前日期如果不是 31 號, 是沒問題的,是 31 號就會有問題:
// 比如今天是 2018-09-30 號,前一個月應(yīng)該是 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 號,所以結(jié)果 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:002. 正確的方法:
2.1 方法一
原理: 當(dāng)前時間減去當(dāng)前時間的天數(shù)
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:002.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最后
技術(shù)文章更新地址:github
對 全棧開發(fā) 有興趣的朋友可以掃下方二維碼關(guān)注我的公眾號,我會不定期更新有價值的內(nèi)容。
微信公眾號:BiaoChenXuYing分享 前端、后端開發(fā)等相關(guān)的技術(shù)文章,熱點(diǎn)資源,全棧程序員的成長之路。
關(guān)注公眾號并回復(fù) 福利 便免費(fèi)送你視頻資源,絕對干貨。
福利詳情請點(diǎn)擊: 免費(fèi)資源分享--Python、Java、Linux、Go、node、vue、react、javaScript
總結(jié)
以上是生活随笔為你收集整理的js 日期对象 31 号 setMonth 的锅的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件测试结束标准
- 下一篇: ansible-playbook 手工编