Calculate amount of time until the next hour

2019-07-03 21:56发布

I'm working on a busing website project and the buses run every hour. I'm having trouble creating a widget that finds the time between now and the next hour, so that it is clear when the next bus will run. My client requires that it is in javascript. Any suggestions? Thanks in advance.

5条回答
Animai°情兽
2楼-- · 2019-07-03 22:23

Lots of answers, a really simple function to get the rounded minutes remaining to the next hour is:

function minsToHour() {
  return 60 - Math.round(new Date() % 3.6e6 / 6e4);
}
查看更多
Animai°情兽
3楼-- · 2019-07-03 22:26

you have the Date object in Javascript, you could do something like:

var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var response = "it will be " + (60 - mins - 1) + " minutes and " + (60 - secs) + " seconds until the next bus";

of course you will have to work more on those calculations, but that's how you work with time in javascript

查看更多
劫难
4楼-- · 2019-07-03 22:33
function getMinutesUntilNextHour() { return 60 - new Date().getMinutes(); }

Note that people who's system clocks are off will miss their bus. It might be better to use the server time instead of the time on the client's computer (AKA at least partly a non-client-side-javascript solution).

查看更多
啃猪蹄的小仙女
5楼-- · 2019-07-03 22:36

To know exactly the miliseconds from now to the next hour:

function msToNextHour() {
    return 3600000 - new Date().getTime() % 3600000;
}

Please note this will strictly tell you how many second until NEXT hour (if you run this at 4:00:00.000 it will give you exactly one hour).

查看更多
何必那么认真
6楼-- · 2019-07-03 22:38

Either of the other two answers will work well, but are you aware of the docs available to you about all the other nice things date is JS can do for you?

Mozilla Date Docs

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

查看更多
登录 后发表回答