在我的javascript项目中,我想检查时间差是否小于1秒。我用时刻来获得这种差异。这是我编写的函数来实现它。
const withinOneSecond = (time) => {
const currentTime = moment();
return time + 1000 < currentTime;
};
但这并没有按预期工作。如何检查给定时间是否在当前时间的一秒之内?
最佳答案
您可以使用moment#diff
。
例如,我在日期中添加了秒,并通过 .diff
传递 秒
作为第二个参数来获取差异,应该返回以秒为单位的差异
var a = moment();
var b = moment().add(1, 'seconds');
console.log(b.diff(a, 'seconds'))
<script src="https://momentjs.com/downloads/moment.js"></script>
支持的测量包括年
、月
、周
、天
、小时
、分钟
和秒
。 Here
对于您的特定情况,您应该做类似的事情
const withinOneSecond = (time) => {
const currentTime = moment();
return currentTime.diff(time, 'seconds') == 1
};
var time = moment().add(1, 'seconds');
let results = withinOneSecond(time);
console.log(results);
<script src="https://momentjs.com/downloads/moment.js"></script>
关于javascript - 检查瞬间时间差是否小于1秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59749996/