JavaScript获取某个时间到n个月前时间组成的时间数组
代码
//time是date格式时间或字符串,n表示那个月,type是返回结果链接符
getLastNMon (time, n, type = '') { let date = new Date(time) let year = date.getFullYear() let month = date.getMonth() + 1 let arry = [] for (let i = 0; i < n; i++) { if (month <= 0) { year = year - 1 month = month + 12 } if (month < 10) { month = '0' + month } arry.push( year + type + month) month = month - 1 } return arry.reverse() } getLastNMon ('2022-12-08', 5) //[202208,202209,202210,202211,202212]
getLastNMon ('2022-12-08', 5,'-') //[2022-08,2022-09,2022-10,2022-11,2022-12]
getLastNMon ('2022-01', 7) // [202107,202108,202109,202110,202111,202112,202201]
开源中国博客地址:https://my.oschina.net/u/2998098/blog/1540520