日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

js 日期对象 31 号 setMonth 的锅

發(fā)布時間:2024/4/17 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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:00

2. 正確的方法:

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: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

最后

技術(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。