计算页面加载到下一小时的第一分钟之间的秒数

calculate how many seconds between page load and first minute of next hour

本文关键字:一分钟 之间 一小时 加载 计算      更新时间:2023-09-26

我需要使用javascript计算两个时间之间的差异:现在是加载页面的时刻,所以我使用:

now = new(Date).getMinutes()*60;

then是下一个小时的第一分钟。举个例子,我住的地方现在是20:20,然后是21:01。那么我的逻辑将是:

if(then-now>=120){
    diff=120;
}else{
    diff=then-now;
}

当我计算差值时,我需要包括下一个小时的所有第一分钟。最聪明的计算方法是什么?

then = Date(year, month, day, new(Date).getHours()+1, 1, 0, 0);它为您提供了日期对象,所以只需执行它-现在转换为秒(getSeconds)。你应该在+1状态下观看25个小时,这样你才能真正使用:then.setDate(someDate.getHour() + 1);

看起来你的逻辑可能只是min(diff, 120)。请注意,您可能希望更清楚地了解120单元是什么。甚至可以设置一个变量"twminutes =120"或"twoHours=120"。

参见:如何将天数添加到today's date?

= = =更新:也许这段代码更有意义

then = Date(year, month, day, new(Date).getHours(), 0, 0, 0);
then.setDate(then.getHour() + 1);
then.setDate(then.getMinute() +1);
YourLogic = min(then-now, 120)

这看起来不太漂亮,但是一个非常直接的计算下一个小时01分钟的方法如下:

new Date(new Date(new Date(new Date().getTime() + 3600000).setMinutes(1)).setSeconds(0))

这样你就不必处理诸如检查时间和确定日期之类的问题了。

你可以用同样的方法来计算,并检查距离上述时间还有多少秒:

var now = new Date().getTime();
var remainingSeconds = (new Date(new Date(new Date(now + 3600000).setMinutes(1)).setSeconds(0)) - now) / 1000;