简体   繁体   中英

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:

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. 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). You should watch for 25 hours in your +1 so you could actually use: then.setDate(someDate.getHour() + 1);

Also looks like your logic could just be 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".

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:

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM