生成随机日期但从javascript中的数组中排除一些日期

生成随机日期但从javascript中的数组中排除一些日期

问题描述:

我有一个名为 dates 的数组,其中包含一些日期.我想排除这些日期并生成一个从今天开始的新随机日期.

I have an array called dates which contains some dates. I want to exclude those dates and generate a new random date which starts from today.

dates = [20/2/2020,10/2/2019]//需要排除日期

dates = [20/2/2020,10/2/2019] //dates needs to be excluded

到目前为止我已经尝试过,

So far I have tried,

        var new_dif =  Math.random(); //generates random number
        
        var daea = new Date(new_dif); //new random date
        
        alert(daea); //generates new date with year 1970

  1. 从今天开始创建随机日期
  2. 有 while 循环,检查生成的已存在于排除日期数组中(继续循环,直到找到不在日期数组中的日期)

const randomDateFromToday = (exclude_dates, max_days = 365) => {
  const randomDate = () => {
    const rand = Math.floor(Math.random() * max_days) * 1000 * 60 * 60 * 24;
    const dat = new Date(Date.now() + rand);
    return `${dat.getDate()}/${dat.getMonth() + 1}/${dat.getFullYear()}`;
  };
  let rday = randomDate();
  while (exclude_dates.some((date_str) => date_str === rday)) {
    rday = randomDate();
  }
  return rday;
};

dates = ["20/2/2020", "10/2/2019"];
console.log(randomDateFromToday(dates));
console.log(randomDateFromToday(dates));