前端利用JS获取最近1、3、5、n年的开始时间和结束时间

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}`);

完毕!

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>