搜索
您的当前位置:首页正文

JS获取当前日期前一个月日期

来源:榕意旅游网
const getOneMonthAgo = () => {
  // 步骤 1: 创建一个当前日期的对象
  let currentDate = new Date(); // 获取当前日期和时间
  let oneMonthAgo = new Date(currentDate);
  // 步骤 2: 获取当前日期的年份和月份
  let currentYear = currentDate.getFullYear(); 
  // 获取当前年份
  let currentMonth = currentDate.getMonth(); 
  // 获取当前月份(注意:月份从0开始,0表示1月)
  oneMonthAgo.setMonth(currentDate.getMonth() - 1); 
  // 设置为上一个月
  // 步骤 3: 将月份减去一
  if (currentMonth === 0) {
    // 如果当前是1月
    currentYear--; // 年份减去1
    currentMonth = 11; // 设置为12月
  } else {
    currentMonth; // 否则,月份减去1
  }
  // 确保日期是有效的
  if (oneMonthAgo.getDate() !== currentDate.getDate()) {
   // 如果这个月没有同样的日期,则设置为上一个月最后一天
    oneMonthAgo.setDate(0); 
     }
  // 步骤 4: 创建一个新的日期对象
  let lastMonthDate = new Date(
    currentYear,
    currentMonth,
    oneMonthAgo.getDate()
  ); 
  // 创建一个新的日期对象,默认为1号
  // console.log(currentMonth)
  return lastMonthDate;
};

因篇幅问题不能全部显示,请点此查看更多更全内容

Top