Multiple Javascript Countdowns on the Same Page - javascript

Hi I'm trying to add several javascript countdowns to a single html page. I have included the .js file below. Right now my page only displays the first countdown.
function cdtd () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd()',1000);
}
function countdown () {
var end = new Date("May 31, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('countdown()',1000);
}
function cdtd3 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd3()',1000);
}
function cdtd4 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd4()',1000);
}
function cdtd5 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd5()',1000);
}
function cdtd6 () {
var end = new Date("December 25, 2013 00:01:00");
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %=60;
document.getElementById("daysBox").innerHTML = days;
document.getElementById("hoursBox").innerHTML = hours;
document.getElementById("minsBox").innerHTML = minutes;
document.getElementById("secsBox").innerHTML = seconds;
var timer = setTimeout('cdtd6()',1000);
}

There are several problems you need to fix here:
Each of your countdown timers uses the same element IDs when it stores the time strings. That's why only one of them shows up.
If any of your countdowns reaches zero, the document.write() call will erase the entire page.
The code is repeated over and over again. This should be one common function for all your countdowns. (What if you need to add one more? Ten more?)
While multiple timers would work, you don't need them. Run a single timer and update all your displayed times from it.
When you call setInterval(), it's better to pass a function reference as the first parameter instead of a string.
Give those ideas some thought and see what you can come up with, then report back with your new code. :-)

Right now you are referencing one box overwriting each value everytime you call the function.
You want to use a query selector instead of getElementById.
Here is a simple example using jQuery:
var cdtd = function(id,end) {
var start = new Date();
var timeDiff = end.getTime() - start.getTime();
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$( id + " .days").html(days);
$( id + " .hours").html(hours);
$( id + " .minutes").html( minutes);
$( id + " .seconds").html( seconds );
console.log(id + " .hoursBox",$( id + " .hoursBox").length,id,end,hours,minutes,seconds)
var timer = setTimeout(function(){cdtd(id,end)},1000);
}
cdtd("#counter1",new Date("December 25, 2014 00:01:00"));
cdtd("#counter2",new Date("October 31, 2014 00:01:00"));
cdtd("#counter3",new Date("January 1, 2014 00:01:00"));
http://plnkr.co/8LrtWvfGnZWyRYl2RlWd

#Shanimal i m used this code on my website,problem is that when timer reached 0000 then it goes another page and shows deal ended.what i want ,when timer reach 0000 it should must display message on same page on specific div.it should not go for another page.i have tried it by removing
if (timeDiff <= 0) {
clearTimeout (timer);
document.write("Deal Ended");
}
it does not shows any message even when it reached 0000 it start to count again from -1 - 1 -1 -1

Related

APEX countdown timer between dates

I'm trying to display the countdown timer between an enddate/time column and the system date/time column using below code. It's not displaying the timer.
I have created a page item P3_TIMER and it has a column P3_STARTDATE.
var timer;
var endDate = new Date();
endDate.setDate(endDate.getDate()); //End date is the sys date
timer = setInterval(function() {
timeBetweenDates(endDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = :P3_STARTDATE;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
$s('P3_TIMER',timer);
}
It's not possible to mix pl/sql and javascript. They're different languages and run in different environments.
function timeBetweenDates(toDate) {
var dateEntered = :P3_STARTDATE; >>> This is pl/sql
var now = new Date();
The P3_STARTDATE needs to be converted to a javascript date object. That cannot be directly, some parsing is needed as shown in this thread.
For the example below the assumption is made that the date is passed in format DD-MON-YYYY.
var timer;
var endDate = new Date();
endDate.setDate(endDate.getDate()); //End date is the sys date
timer = setInterval(function() {
timeBetweenDates(endDate);
}, 1000);
function parseDate(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var p = s.split('-');
return new Date(p[2], months[p[1].toLowerCase()], p[0]);
}
function timeBetweenDates(toDate) {
var dateEntered = parseDate(apex.item( "P63_DATE" ).getValue() );
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
apex.item("P63_TIMER").setValue(`Days: ${days}, Hours: ${hours}, Minutes: ${minutes}, Seconds: ${seconds}`);
}

Countdown function not working correctly in timeout block

I can't get the second countdown function to work correctly in the first Snippet. I fire off cdtd(); a second time for that. Both cdtd(); functions do not collide and are in inside anonymous functions. When I fire off cdtd(); the first time I get a working countdown timer until 16:00:00. When I fire off it for the second time I will not get a working countdown timer until 17:00:00. This is the actual use case of this question.
Just to made an example flow I made a second snippet. Both cdtd(); do collide eachother but the second cdtd(); function call will give a working countdown timer back. Now I still don't know why it's not working in the first snippet. Havint there a timeOut function I work with.
I'm not sure what is wrong. Anyone has got a clue?
Here is the script. https://jsfiddle.net/3fq2j6a1/
I tried to run the countdown scripts under eachother and that works but I don't need that :) function cdtd() { .. }
Here is a snippet:
// First session
var sessie1 = new Date();
var totsessie1 = new Date(sessie1.getFullYear(), sessie1.getMonth(), sessie1.getDate(), 14, 16, 0, 0) - sessie1;
if (totsessie1 < 0) {
totsessie1 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// First countdown
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 16, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End first countdown
}, totsessie1);
// Second session
var sessie2 = new Date();
var totsessie2 = new Date(sessie2.getFullYear(), sessie2.getMonth(), sessie2.getDate(), 14, 17, 0, 0) - sessie1;
if (totsessie2 < 0) {
totsessie2 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// Second countdown
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 17, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End second countdown
}, totsessie2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<span id="time"></span>
Here is the snippet of the code when I use the countdown scripts under eachother.
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 15, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " min and " + seconds + " seconds to go! (countdown to line 49)";
timer = setTimeout(cdtd, 1000);
}
cdtd();
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 16, 0, 0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " min and " + seconds + " seconds to go! (countdown to line 49)";
timer = setTimeout(cdtd, 1000);
}
cdtd();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="test1">This is a paragraph.</p>
<span id="time"></span>
https://jsfiddle.net/edfcLzhw/
But I need them inside the session blocks. When doing that I will get a different time left with the second countdown timer. totsessie1(); totsessie2();
The countdown script comes from: Javascript countdown defined with hours
I solved this for now. I did not make the code correctly on 2 points.
First thing. I used the function totsessie1() also being the second totsessie1() function. I changed the second to totsessie2(). I also didn't use clearInterval(timer); before running the second cdtd();.
Here is a working snippet of the end goal:
// First session
var sessie1 = new Date();
var totsessie1 = new Date(sessie1.getFullYear(), sessie1.getMonth(), sessie1.getDate(), 15, 25, 0, 0) - sessie1;
if (totsessie1 < 0) {
totsessie1 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// First countdown
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(),now.getMonth(),now.getDate(),16,0,0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End first countdown
}, totsessie1);
// Second session
var sessie2 = new Date();
var totsessie2 = new Date(sessie2.getFullYear(), sessie2.getMonth(), sessie2.getDate(), 15, 26, 0, 0) - sessie2;
if (totsessie2 < 0) {
totsessie2 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function() {
document.getElementById("test1").innerHTML = "Message.";
// Second countdown
clearInterval(timer);
function cdtd() {
var now = new Date();
var dolazak = new Date(now.getFullYear(),now.getMonth(),now.getDate(),17,0,0);
var timeDiff = dolazak.getTime() - now.getTime();
if (timeDiff <= 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '';
}
//if(minutes < 2){document.getElementById(id).style.color="#ff0000";};
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
document.getElementById('time').innerHTML = " Still " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds to go!";
timer = setTimeout(cdtd, 1000);
}
cdtd();
// End second countdown
}, totsessie2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p id="test1">This is a paragraph.</p>
<span id="time"></span>
</body>
</html>
JSFiddle: https://jsfiddle.net/nwvk8h12/

Showing a countdown when there are less than 24 hours remaining

I am trying to get my countdown clock to appear only when there are less than 24 hours remaining.
I didn't write the original code. I think it should be...
if (distance < end + ???) {
But i'm not sure what to add ???. Here is the full code...
var end = new Date('05/03/2020 20:00 UTC+1');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
// When countdown over show finished
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML =
"Finished!";
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
// Only show countdown is less than 24 hours remains
if (distance < end + ???) {
// document.getElementById('countdown').innerHTML = days + ':';
document.getElementById('countdown').innerHTML = hours + ' : ';
document.getElementById('countdown').innerHTML += minutes + ' : ';
document.getElementById('countdown').innerHTML += seconds + '';
}
}
timer = setInterval(showRemaining, 1000);
https://jsfiddle.net/yvb4dahn/3/
It works if you change your condition to this one if (distance < 86400000) {. That number is 24h in milliseconds.
var end = new Date('05/03/2020 10:00 UTC+1');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
// When countdown over show finished
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML =
"Finished!";
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
// Only show countdown is less than 24 hours remains
if (distance < 86400000) {
// document.getElementById('countdown').innerHTML = days + ':';
document.getElementById('countdown').innerHTML = hours + ' : ';
document.getElementById('countdown').innerHTML += minutes + ' : ';
document.getElementById('countdown').innerHTML += seconds + '';
}
}
timer = setInterval(showRemaining, 1000);
<div id="countdown"></div>
More info about js dates and formats:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope it helped you :)
You can use this to calculate difference in time:
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date('05/03/2020 20:00 UTC+1');
var secondDate = new Date();
var diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
This will give you result of 1.
So what you need to to is:
if (diffDays < 2 && diffDays > 0)
It will start only if one day is remaining.
var end = new Date('05/03/2020 20:00 UTC+1');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
// When countdown over show finished
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML =
"Finished!";
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
// Only show countdown is less than 24 hours remains
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date('05/03/2020 20:00 UTC+1');
var secondDate = new Date();
var diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
if (diffDays < 2 && diffDays > 0) {
// document.getElementById('countdown').innerHTML = days + ':';
document.getElementById('countdown').innerHTML = hours + ' : ';
document.getElementById('countdown').innerHTML += minutes + ' : ';
document.getElementById('countdown').innerHTML += seconds + '';
}
}
timer = setInterval(showRemaining, 1000);
<div id="countdown"></div>

How can I convert milliseconds to "hhmmss" format using javascript?

I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.
I have the currentTime in milliseconds
var currentTime = new Date().getTime()
and I have futureTime in milliseconds
var futureTime = '1432342800000'
I wanted to get difference in millisecond
var timeDiff = futureTime - currentTime
the the timeDiff was
timeDiff = '2568370873'
I want to know how many hours, minutes, seconds it is.
Could anyone help?
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours
updated
function msToHMS( ms ) {
// 1- Convert to seconds:
let seconds = ms / 1000;
// 2- Extract hours:
const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
alert( hours+":"+minutes+":"+seconds);
}
const timespan = 2568370873;
msToHMS( timespan );
Demo
If you are confident that the period will always be less than a day you could use this one-liner:
new Date(timeDiff).toISOString().slice(11,19) // HH:MM:SS
N.B. This will be wrong if timeDiff is greater than a day.
Convert ms to hh:mm:ss
function millisecondsToHuman(ms) {
const seconds = Math.floor((ms / 1000) % 60);
const minutes = Math.floor((ms / 1000 / 60) % 60);
const hours = Math.floor((ms / 1000 / 3600 ) % 24)
const humanized = [
pad(hours.toString(), 2),
pad(minutes.toString(), 2),
pad(seconds.toString(), 2),
].join(':');
return humanized;
}
=
function msToHMS( duration ) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((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 ;
}
Converts milliseconds to a string in the format hh:mm:ss. Here's my version:
function HHMMSSFromMilliseconds(ms) {
// 1- Convert to seconds:
var seconds = ms / 1000;
// 2- Extract hours:
var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours
// 3- Extract minutes:
var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = parseInt(seconds % 60);
// 5 - Format so it shows a leading zero if needed
let hoursStr = ("00" + hours).slice(-2);
let minutesStr = ("00" + minutes).slice(-2);
let secondsStr = ("00" + seconds).slice(-2);
return hoursStr + ":" + minutesStr + ":" + secondsStr
}
let timespan = 23570 * 1000;
let formattedTime = HHMMSSFromMilliseconds(timespan);
console.log(formattedTime);
Convert millis to DD(days):HH:MM:SS
function formatTime(timeMS) {
const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
const days = Math.floor(seconds / SEC_IN_DAY);
seconds = Math.floor(seconds % SEC_IN_DAY);
const hours = Math.floor(seconds / SEC_IN_HOUR);
seconds = Math.floor(seconds % SEC_IN_HOUR);
const minutes = Math.floor(seconds / SEC_IN_MIN);
seconds = Math.floor(seconds % SEC_IN_MIN);
const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
.map(item => item < 10 ? '0' + item : item.toString());
return dd + ':' + hh + ':' + mm + ':' + ss;
}
The difference in time is in milliseconds:
Get time difference between two dates in seconds
to get the difference you have to use math.floor()
http://www.w3schools.com/jsref/jsref_floor.asp
var secDiff = Math.floor(timeDiff / 1000); //in s
var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
var timediff = futureTime - currentTime
long seconds = (long) (timediff / 1000) % 60 ;
long minutes = (long) ((timediff / (1000*60)) % 60);
long hours = (long) ((timediff / (1000*60*60)) % 24);
if(hours>0)
time = hours+" hrs : "+minutes+" mins";
else if(minutes>0)
time = minutes+" mins";
else if(seconds>0)
time = seconds+" secs";
Here is a simple function
function simplifiedMilliseconds(milliseconds) {
const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
const totalHours = parseInt(Math.floor(totalMinutes / 60));
const days = parseInt(Math.floor(totalHours / 24));
const seconds = parseInt(totalSeconds % 60);
const minutes = parseInt(totalMinutes % 60);
const hours = parseInt(totalHours % 24);
let time = '1s';
if (days > 0) {
time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
} else if (hours > 0) {
time = `${hours}h:${minutes}m:${seconds}s`;
} else if (minutes > 0) {
time = `${minutes}m:${seconds}s`;
} else if (seconds > 0) {
time = `${seconds}s`;
}
return time;
}

PHP / Javascript create countdown between 2 times

I currently have many issues trying to think of how to create this script.
I currently have 2 variables :
$curHour = "15:25:00";
$endHour = "16:25:00";
I am struggling to find how to create a countdown specifcally between these times.
I would appreciate any help.
Greetings Glenn
I have just finished in javascript, but the code seems a little long.
html:
<div id="process"></div>
javascript:
var process = document.getElementById('process');
var cur = '15:25:00';
var end = '16:25:00';
cur = cur.split(':');
end = end.split(':');
var x = parseInt(cur[0], 10)*3600+parseInt(cur[1], 10)*60+parseInt(cur[2], 10);
var y = parseInt(end[0], 10)*3600+parseInt(end[1], 10)*60+parseInt(end[2], 10);
showTime(y);
var timer = setInterval(function(){
y--;
showTime(y);
if(y<=x){
clearInterval(timer);
}
}, 1000);
function showTime(diff){
var hour = parseInt(diff/3600, 10);
var minute = parseInt((diff - hour*3600)/60, 10);
var second = diff - hour*3600-minute*60;
hour = hour<10 ? '0'+hour : hour;
minute = minute<10 ? '0'+minute : minute;
second = second<10 ? '0'+second : second;
var time = hour+':'+minute+':'+second;
process.innerHTML = time;
}
You can try like below,
setInterval(function () {
var end = <?php echo strtotime('16:25:00')*1000;?>;//Javascriptcomapatible time
var current = new Date().getTime(); //Current timestamp
var seconds_left = (end - current) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
console.log(days + "d, " + hours + "h,"+ minutes + "m, " + seconds + "s");
}, 1000);

Categories

Resources