1.获取最近1年的开始时间和结束时间
function getLastYearStartAndEnd() {const currentDate = new Date();const currentYear = currentDate.getFullYear();const currentMonth = currentDate.getMonth() + 1;const lastYearStart = new Date(currentYear - 1, currentMonth, 1);const lastYearEnd = new Date(currentYear, currentMonth - 1, 1);const formatDate = (date) => {const year = date.getFullYear();const month = date.getMonth() + 1;return `${year}-${month.toString().padStart(2, '0')}`;};return {startTime: formatDate(lastYearStart),endTime: formatDate(lastYearEnd),};
}const { startTime, endTime } = getLastYearStartAndEnd();
console.log(`startTime: ${startTime}`);
console.log(`endTime: ${endTime}`);
1.获取最近n年的开始时间和结束时间,只需要对上面的方法传递一个参数即可
function getLastYearStartAndEnd(n_years) {const currentDate = new Date();const currentYear = currentDate.getFullYear();const currentMonth = currentDate.getMonth() + 1;const lastYearStart = new Date(currentYear - parseInt(n_years), currentMonth, 1);const lastYearEnd = new Date(currentYear, currentMonth - 1, 1);const formatDate = (date) => {const year = date.getFullYear();const month = date.getMonth() + 1;return `${year}-${month.toString().padStart(2, '0')}`;};return {startTime: formatDate(lastYearStart),endTime: formatDate(lastYearEnd),};
}const { startTime, endTime } = getLastYearStartAndEnd();
console.log(`startTime: ${startTime}`);
console.log(`endTime: ${endTime}`);
完毕!