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