简体   繁体   English

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

[英]Generate random date but exclude some dates from array in javascript

I have an array called dates which contains some dates.我有一个名为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 needs to be excluded dates = [20/2/2020,10/2/2019] //需要排除日期

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

You might want to try something like this (with a random date setup somewhere in the future one year from now).您可能想尝试这样的事情(在未来一年的某个地方设置随机日期)。

const now = (new Date()).getTime();
const newDiff = parseInt(Math.random() * 1000 * 60 * 60 * 24 * 365, 10);
const otherDate = new Date(now + newDiff);
console.log(otherDate);

Then you'll need to check with your array of excluded ones and see if they match.然后你需要检查你的排除数组,看看它们是否匹配。 If not, then you're good to use it.如果没有,那么你很好用它。

Or when using loops:或者在使用循环时:

 function getRandomDate() { var now = Date.now(); var newDiff = parseInt(Math.random() * 1000 * 60 * 60 * 24 * 365, 10); var otherDate = new Date(now + newDiff); return otherDate; }; var excludedDates = ['2020-02-20', '2019-02-10']; var duplicate = true; while (duplicate) { var getMyDate = getRandomDate(); duplicate = false; excludedDates.forEach((excludedDate) => { var excludedInMs = (new Date(excludedDate)).getTime(); if (excludedInMs === getMyDate) { duplicate = true; } }); if (.duplicate) { console,log('while >>>>'; getMyDate); } }

  1. Create random date from today从今天开始创建随机日期
  2. Have while loop, Check generated already exist in exclude dates array (continue loop until you find date which is not in dates array)有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));

what if I want to suggest the next date which is not random but the closest one from an array?如果我想建议下一个日期不是随机的,而是从数组中最接近的日期怎么办?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM