简体   繁体   中英

Generate random date but exclude some dates from array in javascript

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 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

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)

 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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