JavaScript获取某个时间到n天前时间组成的数组
代码
getLastNDay (time, n, type = '') { let arry = [] for (let i = 0; i < n; i++) { let date = new Date(time) date.setDate(date.getDate() - i) let year = date.getFullYear() let mon = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1 var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() arry.push(year + type + mon + type + d) } return arry.reverse() } getLastNDay(2022-01-01,5)//['20211228', '20211229', '20211230', '20211231', '20220101'] getLastNDay(2022-01-01,5,'/')//['2021/12/28', '2021/12/29', '2021/12/30', '2021/12/31', '2022/01/01']
开源中国博客地址:https://my.oschina.net/u/2998098/blog/1540520