/**
* 根据类型获取对应的时间段
* @param {number} type - 时间段类型:1-本月,2-上个月,3-近三个月,4-近一年
* @returns {Object} 包含start和end的日期对象 { start: Date, end: Date }
* @throws {Error} 当type不合法时抛出错误
*/
function getTimePeriod(type) {
const now = new Date();
let start, end;
switch (type) {
// 1-本月
case 1:
start = new Date(now.getFullYear(), now.getMonth(), 1);
end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
break;
// 2-上个月
case 2:
const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1);
start = new Date(lastMonth.getFullYear(), lastMonth.getMonth(), 1);
end = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0, 23, 59, 59, 999);
break;
// 3-近三个月
case 3:
const threeMonthsAgo = new Date(now);
threeMonthsAgo.setMonth(now.getMonth() - 2); // 减2是因为从当月开始算第一个月
start = new Date(threeMonthsAgo.getFullYear(), threeMonthsAgo.getMonth(), 1);
end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
break;
// 4-近一年
case 4:
const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth());
start = new Date(oneYearAgo.getFullYear(), oneYearAgo.getMonth(), 1);
end = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
break;
default:
throw new Error('无效的类型,请传入1-4之间的数字(1:本月, 2:上个月, 3:近三个月, 4:近一年)');
}
return { startTime: moment(start).format('YYYY-MM-DD'), endTime: moment(end).format('YYYY-MM-DD') };
}
本文链接:https://blog.smallhao.fun/?id=37 转载需授权!
暂无评论
发表评论