为什么这个函数不返回 > 的随机时间?现在起? [英] Why do this function doesn't return a random time that's > from now?
本文介绍了为什么这个函数不返回 > 的随机时间?现在起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用以下函数(取自另一个答案)来获得 > 的随机时间.从现在开始和每小时范围内.
I'm trying to use following function (taken from an another answer) to get a random time that's > from now and within a hourly range.
我不知道需要放入 startHour
我的时间是美国东部时间下午 4 点,我在那里放了 16 个,在 hourRange
中放了 5 个,但它给我的值小于那个.
My time is 4 PM EST US and I put 16 there and 5 to the hourRange
but it gives me values that's less than that.
function randomTime(rangeOfDays = 0, startHour, hourRange){
var today = new Date(Date.now());
return new Date(today.getYear()+1900,today.getMonth(), today.getDate()+Math.random() *rangeOfDays, Math.random()*hourRange + startHour, Math.random()*60)
}
该答案的链接,答案
推荐答案
这里只使用 Ticks 来解决问题.哪个更容易管理.
Here this deals with the problem by working with Ticks only. Which is easier to manage.
const getRandomTime = (offsetHour = 0, rangeInHours = 2) => {
const curTicks = Date.now() + 0 * (offsetHour*60*60*1000);
const addTicks = (Math.random()*rangeInHours)*60*60*1000;
return new Date(curTicks + addTicks);
};
console.log((new Date()));
for(let i=0; i<10;i++) {
console.log( getRandomTime(1, 2+i));
}
这篇关于为什么这个函数不返回 > 的随机时间?现在起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文