js 獲取最近的時間思路是
1. 獲取當前時間的時間戳
2. 在時間戳 減去 3600 * 1000 * 24 *天數
3.在把獲取到的時間戳轉回日期格式
4.藉助for 循環循環需要的天數即可獲得從當前時間到目標時間的數組
下面上代碼
const defaultDay = (day) => {
if (!day) {
return
}
// const end = new Date()
const arry = []
for (let index = day - 1; index >= 0; index--) {
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * index)
arry.push(dateFormat('YYYY-mm-dd', start))
}
return arry
}
// 格式化時間
const dateFormat = (fmt, date) => {
let ret
const opt = {
'Y+': date.getFullYear().toString(), // 年
'm+': (date.getMonth() + 1).toString(), // 月
'd+': date.getDate().toString(), // 日
'H+': date.getHours().toString(), // 時
'M+': date.getMinutes().toString(), // 分
'S+': date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以繼續添加,必須轉化成字符串
}
for (const k in opt) {
ret = new RegExp(`(${k})`).exec(fmt)
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
}
}
return fmt
}