2024年07月27日 建站教程
用JS实现获取2个时间点之间的日期、月份、年份(包括区间自身),代码如下:
1、获取日期
function getTimeTwo(start, end) { let diffdate = new Array(); let arr = [] let i = 0; while (start <= end) { diffdate[i] = start; let stime_ts = new Date(start).getTime(); let next_date = stime_ts + (24 * 60 * 60 * 1000); let next_dates_y = new Date(next_date).getFullYear() + '-'; let next_dates_m = (new Date(next_date).getMonth() + 1 < 10) ? '0' + (new Date(next_date).getMonth() + 1) + '-' : (new Date(next_date).getMonth() + 1) + '-'; let next_dates_d = (new Date(next_date).getDate() < 10) ? '0' + new Date(next_date).getDate() : new Date(next_date).getDate(); start = next_dates_y + next_dates_m + next_dates_d; i++; } return diffdate; } console.log(getTimeTwo('2022-01-12','2022-01-31'))
2、获取月份
function getMonthBetween(start, end) { let result = []; let min = new Date(start); let max = new Date(end); let curr = min; while (curr <= max) { let month = new Date(curr).getMonth() + 1; let t = "" if (month < 10) { t = '0' + month } else t = month let str = curr.getFullYear() + "-" + (t); let s = curr.getFullYear() + "-0"; if (str == s) { str = curr.getFullYear() + "-12"; } result.push(str); curr.setMonth(month); } return result; } console.log(getMonthBetween('2022-01','2023-12'))
3、获取年份
function getYearBetween(start, end){ let result = []; let min = new Date(start).getFullYear(); let max = new Date(end).getFullYear(); while (min <= max) { result.push(min); min = (Number(min) + 1) } return result; } console.log(getYearBetween('2021-01-01','2022-01-01'))
本文链接:http://so.lmcjl.com/news/9283/