I'm looking for a way to have a countdown timer that displays more than 24 hours instead of displaying days when there is more than one day left. In short, it shows 26:04:32 instead of 01:02:04:32.
I was working with this, but got stuck.
<script>
(function () {
var deadline = '2022/09/07 00:00';
function pad(num, size) {
var s = "0" + num;
return s.substr(s.length - size);
}
// fixes "Date.parse(date)" on safari
function parseDate(date) {
const parsed = Date.parse(date);
if (!isNaN(parsed)) return parsed
return Date.parse(date.replace(/-/g, '/').replace(/[a-z]+/gi, ' '));
}
function getTimeRemaining(endtime) {
let total = parseDate(endtime) - Date.parse(new Date())
let seconds = Math.floor((total / 1000) % 60)
let minutes = Math.floor((total / 1000 / 60) % 60)
let hours = Math.floor((total / (1000 * 60 * 60)) % 24)
let days = Math.floor(total / (1000 * 60 * 60 * 24))
return { total, days, hours, minutes, seconds };
}
function clock(id, endtime) {
let days = document.getElementById(id + '-days')
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes')
let seconds = document.getElementById(id + '-seconds')
var timeinterval = setInterval(function () {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
clearInterval(timeinterval);
} else {
days.innerHTML = pad(time.days, 2);
hours.innerHTML = pad((time.hours, 2) + (24 * (time.days, 2)), 2);
minutes.innerHTML = pad(time.minutes, 2);
seconds.innerHTML = pad(time.seconds, 2);
}
}, 1000);
}
clock('js-clock', deadline);
})();
</script>
Just don't modulo (%) the hours with 24, and get rid of everything related to days:
let hours = Math.floor((total / (1000 * 60 * 60))); // will happily go > 24
Related
Countdown works fine but I need to output Text for exaple...
If 1 day is show then output Day if more days then Days, the same with hours, minutes and seconds..
function getTimeRemaining(endtime) {
const total = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((total / 1000) % 60);
const minutes = Math.floor((total / 1000 / 60) % 60);
const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
const days = Math.floor(total / (1000 * 60 * 60 * 24));
return {
total,
days,
hours,
minutes,
seconds
};
}
function initializeClock(id, endtime) {
function updateClock() {
const t = getTimeRemaining(endtime);
document.querySelector('.days').innerHTML = t.days;
document.querySelector('.hours').innerHTML = t.hours;
document.querySelector('.mins').innerHTML = t.minutes;
document.querySelector('.secs').innerHTML = ('0' + t.seconds).slice(-2);
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
const timeinterval = setInterval(updateClock, 1000);
}
const countdown = "November 18 2022 19:00:00";
initializeClock("#codo", countdown);
1 Days 2 Hours 1 Minute 30 Seconds
I tried eg:
if(days > 1) { var day = 'Days'; } else { var day = 'Day'; }
But where exactly do I have to install it to output the text, I've tried a few things but non-stop initialize error given.
updateClock sets the output, specifically the 4 lines begining with document.querySelector. They set the content of 4 elements in your HTML.
function updateClock() {
const t = getTimeRemaining(endtime);
/* determine plural/singular word */
const days = t.days>1?" days":" day"
const hours = t.hours>1?" hours":" hour"
const minutes = t.minutes>1?" minutes":" minute"
const seconds = t.seconds>1?" seconds":" second"
/* append word to value */
document.querySelector('.days').innerHTML = t.days + days;
document.querySelector('.hours').innerHTML = t.hours + hours;
document.querySelector('.mins').innerHTML = t.minutes + minutes;
document.querySelector('.secs').innerHTML = ('0' + t.seconds).slice(-2) + seconds;
if(t.total <= 0) {
clearInterval(timeinterval);
}
}
innerHTML as the name suggests, sets the HTML inside the element. (as a string).
element.innerHTML = `Hello <div class="smallWord">World</div>`
I have jquery countdown function with below code:
$.fn.countdown = function(toTime, callback){
let $el = $(this);
var intervalId;
let timeUpdate = () => {
var now = new Date().getTime();
var distance = toTime - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if(distance < 0){
clearInterval(intervalId);
}
else{
var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
$el.html(value);
}
if(callback) callback();
}
timeUpdate();
intervalId = setInterval(timeUpdate, 1000);
};
$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime());
$('#my_div2').countdown(new Date("Jun 23, 2022 22:20:25").getTime());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>
Now I need to add callback function if the time has finished.
My idea is like this:
$('#my_div').countdown(new Date("Jun 23, 2022 22:37:25").getTime(), function(){
callback: function() {
alert("Counting Finish");
}
});
Is there any way to implement that callback?
Your code is almost there, there's just two issues. Firstly you need to invoke the callback argument from within the distance < 0 block, as that's what determines when the countdown has ended. Secondly you need to provide an actual callback argument to the countdown() call.
Note in the following example I made the countdowns only a few seconds from the current date to make the demo clearer.
$.fn.countdown = function(toTime, callback) {
let $el = $(this);
var intervalId;
let timeUpdate = () => {
var now = new Date().getTime();
var distance = toTime - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (distance < 0) {
clearInterval(intervalId);
callback && callback();
} else {
var value = days + "<sup>d</sup> " + (hours > 9 ? hours : '0' + hours) + ":" + (minutes > 9 ? minutes : '0' + minutes) + ":" + (seconds > 9 ? seconds : '0' + seconds);
$el.html(value);
}
}
timeUpdate();
intervalId = setInterval(timeUpdate, 1000);
};
var date1 = new Date();
date1.setSeconds(date1.getSeconds() + 5);
$('#my_div').countdown(date1.getTime(), () => console.log('first countdown elapsed!'));
var date2 = new Date();
date2.setSeconds(date2.getSeconds() + 10);
$('#my_div2').countdown(date2.getTime(), () => console.log('second countdown elapsed!'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="my_div"></div>
<div id="my_div2"></div>
I want to create a countdown to a set date and time. When the deadline arrives the timer will reset to 24 hours. Every day it will count down to 14:15.
This is the code below. Thanks in advance.
(function() {
var deadline = '2021/12/30 14:15';
function pad(num, size) {
var s = "0" + num;
return s.substr(s.length - size);
}
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date()),
seconds = Math.floor((t / 1000) % 60),
minutes = Math.floor((t / 1000 / 60) % 60),
hours = Math.floor((t / (1000 * 60 * 60)) % 24),
days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function clock(id, endtime) {
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes');
var timeinterval = setInterval(function() {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
deadline = "een datum"
clearInterval(timeinterval);
} else {
hours.innerHTML = pad(time.hours, 2);
minutes.innerHTML = pad(time.minutes, 2);
}
}, 1000);
}
clock('js-clock-header', deadline);
function clocks(id, endtime) {
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes');
var timeinterval = setInterval(function() {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
clearInterval(timeinterval);
} else {
hours.innerHTML = pad(time.hours, 2);
minutes.innerHTML = pad(time.minutes, 2);
}
}, 1000);
}
clocks('js-clock', deadline);
})();
<span id="js-clock-header-hours"></span>:<span id="js-clock-header-minutes"></span><br />
<span id="js-clock-hours"></span>:<span id="js-clock-minutes"></span>
I want to find difference between two time with milliseconds value in Javascript.
As you can see below snapshot, where I calculated two time values in Excel.
My expectation exactly same calculated value with JS code.
I tried some code snippet but I got slightly difference in seconds.
var d1 = '2020-12-15 01:00:23.788';
var d2 = '2020-12-15 01:00:55.482';
var date1 = new Date(d1);
var date2 = new Date(d2);
//date2 += 500;
//date2 = new Date(date2);
//date2.setMilliseconds(5);
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms / 1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms / 60;
var hours = Math.floor(difference_ms % 24);
var demo = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds.' + difference_ms;
document.getElementById("demo").innerHTML = demo;
<h2>JavaScript new Date()</h2>
<p>new Date() creates a new date object with the current date and time:</p>
<p id="demo"></p>
OUTPUT:
new Date() creates a new date object with the current date and time:
0 hours, 0 minutes, and 31 seconds.0.008803888888888889
JS does the same when correctly implemented
I tried with more interesting times
// Excel: 02:10:55,482 - 01:09:23,788 = 01:01:31,694
const fmtTime = date => {
const hours = `0${date.getHours() - 1}`.slice(-2);
const minutes = `0${date.getMinutes()}`.slice(-2);
const seconds = `0${date.getSeconds()}`.slice(-2);
const ms = `00${date.getMilliseconds()}`.slice(-3);
return `${hours}:${minutes}:${seconds}.${ms}`
}
const from = "01:09:23,788"
const to = "02:10:55.482"
const re = /(\d{2}):(\d{2}):(\d{2}).(\d{3})/;
const [m1, fromhh, frommm, fromss, fromms] = from.match(re);
const [m2, tohh, tomm, toss, tomms] = to.match(re);
// method one
let d = new Date()
d.setHours(fromhh, frommm, fromss, fromms)
const fromTime = d.getTime()
d.setHours(tohh, tomm, toss, tomms)
const toTime = d.getTime()
const diffInMS1 = toTime - fromTime
console.log(diffInMS1)
d = new Date(diffInMS1);
console.log(fmtTime(d))
// Method 2 - Note I need to cast to int where I only add (+fromms)
let fromMS = (fromhh * 60 * 60 * 1000) + (frommm * 60 * 1000) + (fromss * 1000) + +fromms;
let toMS = (tohh * 60 * 60 * 1000) + (tomm * 60 * 1000) + (toss * 1000) + +tomms;
const diffInMS2 = toMS - fromMS;
console.log(diffInMS2)
d = new Date(diffInMS2);
console.log(fmtTime(d))
function splitInNumberArray(str) {
return str
.replace(/(:|\.)/g, " ")
.split(" ")
.map((x) => parseInt(x));
}
function convertToMilliseconds(timeArray) {
return (
timeArray[0] * 60 * 60 * 1000 +
timeArray[1] * 60 * 1000 +
timeArray[2] * 1000 +
timeArray[3]
);
}
function msToTime(duration) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
// This function is taken from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
function parseDuration(duration) {
let remain = duration;
let hours = Math.floor(remain / (1000 * 60 * 60));
remain = remain % (1000 * 60 * 60);
let minutes = Math.floor(remain / (1000 * 60));
remain = remain % (1000 * 60);
let seconds = Math.floor(remain / 1000);
remain = remain % 1000;
let milliseconds = remain;
return {
hours,
minutes,
seconds,
milliseconds,
};
}
function minTwoDigits(n) {
return (n < 10 ? "0" : "") + n;
}
//***************************************
const time1 = "01:00:55.482";
const time2 = "01:00:23.788";
const numberArray1 = splitInNumberArray(time1);
const numberArray2 = splitInNumberArray(time2);
const msTime1 = convertToMilliseconds(numberArray1);
const msTime2 = convertToMilliseconds(numberArray2);
const diff = msTime1 - msTime2;
const { hours, minutes, seconds, milliseconds } = parseDuration(diff);
console.log(
`${time1} - ${time2} = ${minTwoDigits(hours)}:${minTwoDigits(
minutes
)}:${minTwoDigits(seconds)}.${milliseconds}`
);
I tried to make countdown function , It is work unless hour time ! But I want to make 2 hours countdown time , I can't figure more ?
<div id="time"></div>
<script type="text/javascript">
var hour = 2 ;
var min = 30;
var countdown = hour * min * 60 * 1000;
//var countdown = hour * 3600 * min * 60 * 1000; also not working
var timeload = setInterval(function () {
countdown -= 1000;
var hr = Math.floor(countdown/(60 * 60 * 1000));
var min = Math.floor(countdown / (60 * 1000));
var sec = Math.floor((countdown - (min * 60 * 1000)) / 1000);
if (countdown <= 0) {
alert("Timeout !");
clearInterval(timeload);
}
else {
$("#time").html("<font color='red'>Allowed Time </font>" + hr + " : " + min + " : " + sec);
}
}, 1000);
</script>
Actual Started Time
Allowed Time 0 : 59 : 59
Expected Start Time Allowed Time 2 : 29 : 59
you can try this solution, you have an error on calculation time (hr, min, sec) it should modulus to maximum each value and also you wrong when convert hour and min to millisecond
var hour = 2 ;
var min = 30;
var countdown = (hour * 60 * 60 * 1000) + (min * 60 * 1000);
var timeload = setInterval(function () {
countdown -= 1000;
var hr = Math.floor( (countdown / (60 * 60 * 1000)) % 24 );
var min = Math.floor( (countdown / (60 * 1000)) % 60 );
var sec = Math.floor( (countdown / 1000) % 60 );
if (countdown <= 0) {
alert("Timeout !");
clearInterval(timeload);
}
else {
$("#time").html("<font color='red'>Allowed Time </font>" + hr + " : " + min + " : " + sec);
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>
I think your calculations may be wrong. You don't want to multiply the hours by the minutes, but rather add them up in some way.
// useful numbers for calculations into milliseconds
var _1sec = 60 * 1000, _1min = 60 * _1sec, _1hr = 60 * min;
// renamed `hour` to cHR (countdown hour) so I can keep things straight in my head
var total_ms = (cHr * _1hr) + (cMin * _1min);
The hours/minutes/seconds for display also needs reworking.
// Mod (%) takes the remainder after division. So countdown % _1hr takes whatever is left over that doesn't go into whole hours, etc.
hr = Math.floor(countdown / _1hr);
min = Math.floor((countdown % _1hr) / _1min);
sec = Math.floor((countdown % _1min) / _1sec);
an example using diff between start and finish
var hour = 2;
var min = 30;
var finish = new Date();
finish.setHours(finish.getHours() + hour);
finish.setHours(finish.getHours(), finish.getMinutes() + min)
var diff = finish.getTime() - new Date().getTime()
var timeload = setInterval(function() {
diff -= 1000
var s = Math.floor(diff / 1000);
var m = Math.floor(s / 60);
var h = Math.floor(m / 60);
h %= 24;
m %= 60;
s %= 60;
if (diff <= 0) {
alert("FINISH!!");
clearInterval(timeload);
} else {
$("#time").html("<font color='red'>Allowed Time </font>" + h + " : " + m + " : " + s);
}
}, 1000)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>