-- 创造无限可能

js开发技巧:生成近10天的日期

2023-05-25 21:39:07
586 人浏览 0 人点赞
有用,点赞支持一下

场景

一些需要预约的场景,一般需要显示最近10天的时间给用户选择

方案

  1. 获取到今天的时间戳(毫秒),let today = (new Date()).getTime()
  2. 循环10次,每日增加一天的秒数,let nextDay = new Date(today + 86400000)
  3. 格式化日期

    实例

function getDateList(num=15){
    // 获取当前日期
    const currentDate = new Date();
    let list = []
    // 循环生成接下来的 num 天日期
    for (let i = 0; i < num; i++) {
      // 生成日期所需的时间戳
      const timestamp = currentDate.getTime() + i * 24 * 60 * 60 * 1000;

      // 将时间戳转换成日期格式
      const date = new Date(timestamp);

      // 输出日期
      let key = formatDate(date,'MM-dd')
      let value = formatDate(date,'yyyy-MM-dd')
      list.push({key,value})
    }
    return list
}
//格式化时间戳
function formatDate(date, format) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  let result = format.replace(/yyyy/g, year);
  result = result.replace(/MM/g, month);
  result = result.replace(/dd/g, day);
  result = result.replace(/HH/g, hour);
  result = result.replace(/mm/g, minute);
  result = result.replace(/ss/g, second);

  return result;
}