[英]calculate how many seconds between page load and first minute of next hour
I need to calculate a difference between two time using javascript: now is the moment when you load the page so I use: 我需要使用javascript计算两次之间的时差:现在是加载页面的时刻,因此我使用:
now = new(Date).getMinutes()*60;
then is the first minute of the next hour. 然后是下一个小时的第一分钟。 So for example now is 20:20 where I live: then will be 21:01. 例如,现在我住的地方是20:20:然后是21:01。 then my logic will be: 那么我的逻辑将是:
if(then-now>=120){
diff=120;
}else{
diff=then-now;
}
When I calculate the difference I need to include all the first minute of next hour. 当我计算差异时,我需要包括下一小时的所有第一分钟。 What can be the smartest way to calculate then in seconds? 那么几秒钟内最聪明的计算方法是什么?
then = Date(year, month, day, new(Date).getHours()+1, 1, 0, 0);
that gives you the date object, so just do then - now into seconds (getSeconds). 它为您提供了日期对象,所以就去做-现在变成几秒钟(getSeconds)。 You should watch for 25 hours in your +1 so you could actually use: then.setDate(someDate.getHour() + 1);
您应该在+1中观看25个小时,以便实际使用: then.setDate(someDate.getHour() + 1);
Also looks like your logic could just be min(diff, 120)
. 而且看起来您的逻辑可能只是min(diff, 120)
。 Note that you may want to be more clear what unit 120 is in. Could even make a variable "twoMinutes=120" or "twoHours=120". 请注意,您可能想更清楚地知道单元120所在的单元。甚至可以使变量“ twoMinutes = 120”或“ twoHours = 120”。
See: How to add number of days to today's date? 请参阅: 如何将天数添加到今天的日期?
=== Update: Perhaps this code makes more sense ===更新:也许这段代码更有意义
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)
This doesn't look very beautiful, but a very straight-forward way of calculating the 01 minute of the next hour is as follows: 这看起来不太漂亮,但是计算下一个小时的01分钟的一种非常简单的方法如下:
new Date(new Date(new Date(new Date().getTime() + 3600000).setMinutes(1)).setSeconds(0))
This way you won't have to deal with problems like checking the hour 23 and fixing the date. 这样,您就不必处理诸如检查23点和确定日期之类的问题。
You can use this idea to calculate now the same way and check the number of seconds left till the above time: 您现在可以使用此想法以相同的方式进行计算,并检查到上述时间为止还剩多少秒:
var now = new Date().getTime();
var remainingSeconds = (new Date(new Date(new Date(now + 3600000).setMinutes(1)).setSeconds(0)) - now) / 1000;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.