条件:
1、昨天是前推天数的最后一天
2、向前推指定天数
3、获取前推指定天数的第一天和最后一天

/**
 * 时间戳或标准时间字符串转 年月日时分秒
 * @param { number } timestamp 时间戳或标准时间
 * @return 返回年月日时分秒字符串
 */
 const getTimestamp = (timestamp, type = null) => {
  let date = new Date(timestamp);
  let Year = String(date.getFullYear());
  let Moth = String(date.getMonth() + 1).padStart(2, "0");
  let Day = String(date.getDate()).padStart(2, "0");
  let Hour = String(date.getHours()).padStart(2, "0");
  let Minute = String(date.getMinutes()).padStart(2, "0");
  let Seconds = String(date.getSeconds()).padStart(2, "0");
  if (type == "YYYY-MM-DD") {
    return `${Year}-${Moth}-${Day}`;
  } else {
    return `${Year}-${Moth}-${Day} ${Hour}:${Minute}:${Seconds}`;
  }
};

// 前推指定天数的日期
 function getDatesForwardDate(days = 0) {
  const today = new Date();
  const firstDay = new Date(today);
  firstDay.setDate(firstDay.getDate() - days); // 向前推指定天,得到前指定天数的第一天

  const lastDay = new Date(today);
  lastDay.setDate(lastDay.getDate() - 1); // 昨天是前指定天数的最后一天

  const firstDayFormatted = getTimestamp(firstDay, "YYYY-MM-DD");
  const lastDayFormatted = getTimestamp(lastDay, "YYYY-MM-DD");
  return [firstDayFormatted, lastDayFormatted];
}

// 传入多少天就前推多少天
let time1 = getDatesForwardDate(30); // 包含当天,前推30天
let time2 = getDatesForwardDate(7); // 包含当天,前推7天
console.log(time1); // ['2024-10-19', '2024-11-17'] 
console.log(time2); // ['2024-11-11', '2024-11-17']

运行结果:
image.png


兔子先森
417 声望18 粉丝

致力于新技术的推广与优秀技术的普及。