为什么此函数不返回指定范围的时间?

杰夫RTC

考虑以下代码,

// Code from https://stackoverflow.com/a/66035934/14659574
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));
}

它不尊重范围,而是返回超出范围的随机时间。我想要一个范围内的随机时间。

例如,假设我想要一个从现在起 2 小时后的随机时间,但此函数为我提供了从现在起 5 小时后的值。

代码取自我之前的问题看起来答案的作者不活跃,所以我决定提出一个后续问题。

我有计算障碍,无法调试。我什至试图给数字贴上标签,但它无处可去。

这段代码有什么问题?

约旦

我相信这个错误在这部分:Date.now() + 0 * (offsetHour * 60 * 60 * 1000);.

通过将偏移小时数乘以零,您可以有效地将其重置为零并抵消偏移量。

因此,无法从 UTC 更改起点。

随着0 *从方法去除,它按预期工作:

const getRandomTime = (offsetHour = 0, rangeInHours = 2) => {
  // Removed the offending 0 *
  const curTicks = Date.now() + (offsetHour * 60 * 60 * 1000);
  const addTicks = (Math.random() * rangeInHours) * 60 * 60 * 1000;

  return new Date(curTicks + addTicks);

};

// Prints a time between UTC-5 and 1 hour from then.
console.log("Up to one hour from now: ",getRandomTime(-5, 1));

// Prints a time between UTC-5 and 2 hours from then.
console.log("Up to two hours from now: ",getRandomTime(-5, 2));

// Example continues
console.log("Up to three hours from now: ",getRandomTime(-5, 3));
console.log("Up to four hours from now: ",getRandomTime(-5, 4));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章