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

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.

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;

For GMT+0 it would be
const secondUntilEndOfTheDay = 86400 - Math.floor(new Date() / 1000) % 86400;

Related

change days and hours by how time flies

I am getting the elapsed time in minutes, hours and days, between two dates, a past date and the current one, I already get this data, but I want this data to change as the minutes, days and hours increase. For example, when I get to 60 minutes, the time changes to 1 hour and the minutes go to 0, when 24 hours go by, these hours change to a day and the hours go back to 0, and so on, the data I get keeps increasing , how can I do this?
const calculateDate = () => {
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const minutes= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60);
const hours= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / (3600));
const days= Math.floor((currentDate.getTime() - date.getTime()) / (1000*60*60*24));
}
With this, get the minutes, hours and days, but how would you update so that when you reach 60 minutes it goes to one hour and 24 hours to one day?
The JavaScript Date object has built in functions for what you want to do.
var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()
The new Date created in above example is set to the time it was created.
You can get the current time using the Date object itself:
var current = Date()
With your method you always see the full duration just in a different unit.
You have to use the modulo operator to get only the "missing part" (the remainder of the division) to the next unit:
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const dateDiff = (currentDate.getTime() - date.getTime()) / 1000;
const seconds = Math.floor(dateDiff) % 60;
const minutes = Math.floor(dateDiff / 60) % 60;
const hours = Math.floor(dateDiff / (60 * 60)) % 24;
const days = Math.floor(dateDiff / (60 * 60 * 24));

Javascript repeating countdown timer to midday

I am trying to create a javascript countdown which displays the hours and minutes, counting down to midday each day. When midday is reached I would like the timer to reset and start counting down to midday again (obviously to countdown to the following day).
I have the code below, however I just can't get it to work properly, the code works fine after midday however once midnight is reached the count is incorrect.
Here is my code:
function ShowTimes() {
var now = new Date();
var hrtime = now.getHours()
var hrs = 23 - hrtime + 12;
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
var str = '';
str += hrs+' hours '+mins+' minutes';
document.getElementById('countdown').innerHTML = str;
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
Any help is much appreciated! Thanks in advance.
Do you live somewhere that moves clocks forwards/backwards in spring/autumn?
If so, you'll have two days in the year where your hour and minute logic would fail.
Here's a way that works even when the clocks change:
var now = new Date();
var midday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (now.getHours() >= 12 ? 1 : 0), 12);
var millisToMidday = midday.getTime() - now.getTime();
var hours = Math.floor((millisToMidday / (60 * 60 * 1000)))
var minutes = Math.floor((millisToMidday / (60 * 1000))) % 60;
var seconds = Math.floor((millisToMidday / (1000))) % 60;
Change the logic for Hrs calculation as below :
if(hrtime>12)
hrtime=23- hrtime+ 12;
else
hrtime= 12-hrtime;

How to get time length from now back to the start of today (00h:00p:00s) in angularjs

How to get timelength from now back to the start of today (00h:00p:00s) in angularjs?
ex: now is 13:45. So timelength = 13*60 + 45 mins
There is no specificity in angular. Just use the Date object.
var date = new Date();
var timelength = date.getMinutes() + date.getHours() * 60;
Get a new JavaScript date object that represents the time now and then use the getHours and getMinutes functions to enable your calculation.
For example:
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var timeLength = hours*60 + minutes;
Converting a javascript date to a number gives you milliseconds since 1/1/1970 (UTC). You can correct for your time zone if you wish, then just take the modulus of the number of milliseconds in a day to get the number of milliseconds since midnight:
var dt = new Date();
var num = dt - dt.getTimezoneOffset() * 60000; // offset is in minutes
var sec = num / 1000; // seconds
var sinceMidnight = sec % (24 * 60 * 60); // seconds since midnight

Get hour and minute difference between current time and 12pm

I am trying to get the current time difference in hours and minutes between now and 12pm (midday). If it is past 12pm on the current day it must then count down the hours onto the next day.
I have looked around here for a while now and have found many examples on getting date differences but and am unable to get a working solution for time so have been playing around with writing my own. However I am unable to getTime(); to get hours and minutes from the millisecond timestamp on my new dates and am unsure why exactly. Here is my code:
dateone = new Date();
datetwo = new Date();
datetwo = datetwo.setHours(12);
dateone = dateone.getTime();
datetwo = datetwo.getTime();
if(dateone > datetwo) {
var seconds = dateone - datetwo;
} else {
var seconds = datetwo - dateone;
}
var d = seconds;
var minutes=(d/(1000*60))%60;
var hours=(d/(1000*60*60))%24;
var minutesround=Math.floor(minutes);
var hoursround=Math.round(hours);
var endtime = 12;
alert(hours);
alert(minutes);
If anyone is able to spot a better way of doing this, or can suggest anything it would be greatly appreciated!
Thanks,
Simon
Try
var d = new Date(), midDay = new Date();
midDay.setHours(12);
midDay.setMinutes(0);
midDay.setSeconds(0);
if(d > midDay) {
midDay.setDate(midDay.getDate() + 1)
}
var diff = (midDay.getTime() - d.getTime()) / 1000;
var hrs = parseInt(diff / 3600);
diff = diff % 3600;
var minutes = parseInt(diff / 60);
console.log(hrs, minutes)
Demo: Fiddle

Jquery time difference in hours from two fields

I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);

Categories