Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript new Date() - Get seconds until end of the day

Working on a javascript-canvas based clock (classic analog clock view), also displaying the current date below the clock.

I already have this code to get the current time in javascript:

   // get current time
    var date = new Date();
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var seconds = date.getSeconds();
    hours = hours > 12 ? hours - 12 : hours;
    var hour = hours + minutes / 60;
    var minute = minutes + seconds / 60;

Works great, except that I don't know how to get the number in seconds until the end of the day, so I could run an ajax request at 00:00h to update the current date.

The question is, how to get easily the number in seconds until end of the day in javascript?

I plan to start a setTimeout()-function after the clock loaded with the number of seconds left, to update the date when needed.

like image 855
lickmycode Avatar asked Dec 20 '25 02:12

lickmycode


2 Answers

I'm assuming the date you want to change is not from these values. You need to change it in some place not directly related to this clock?

I would suggest to add a function to check if the day has changed and include it when the clock is refreshed.

In any case, getting the seconds to the end of the day should be something like

var secondsUntilEndOfDate = ( (24*60*60) - ( (hours*60*60) + (minutes*60) + seconds ) );

Javascript:

var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var secondsUntilEndOfDate = (24*60*60) - (h*60*60) - (m*60) - s;
like image 83
Marcelo Avatar answered Dec 22 '25 14:12

Marcelo


For GMT+0 it would be

const secondUntilEndOfTheDay = 86400 - Math.floor(new Date() / 1000) % 86400;
like image 33
lis-dev Avatar answered Dec 22 '25 14:12

lis-dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!