如何解决生成随机日期,但从JavaScript中的数组中排除一些日期
我有一个名为 dates 的数组,其中包含一些日期。我想排除这些日期,并生成一个从今天开始的新随机日期。
dates = [20/2 / 2020,10 / 2/2019] // 需要排除的日期
到目前为止,我已经尝试过了
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
解决方法
您可能想尝试类似的操作(从现在开始,在未来一年的某个地方设置一个随机日期)。
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);
然后,您需要检查排除的阵列,看看它们是否匹配。如果没有,那您就很好用了。
或者在使用循环时:
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);
}
}
,
- 从今天开始创建随机日期
- 具有while循环,生成的检查已存在于排除日期数组中(继续循环直到找到不在dates数组中的日期)
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));
,
如果我要建议下一个日期不是随机的而是数组中最接近的日期怎么办?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。