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>`
Related
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
I have ecommerce website. In that for same day delivery need to order before 11. So before 30 minutes of the end time(i.e. 11) i want to show that timer section.
Below code I am trying But getting issue how to set timer functionality.
setInterval(function(){
var secs = 1800;
var date = new Date;
// date.setTime(result_from_Date_getTime);
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();
console.log("Hour"+hour+"Minutes"+minutes+"seconds"+seconds);
// console.log(minutes);
// console.log(seconds);
if(hour == 10 && minutes>=30)
{
var mins = secs / 60;
console.log("Timer"+mins);
$('.top-header-content1').removeClass('hide-ticker1');
}
else if (hour >= 11){
console.log("hii11");
$('.top-header-content1').addClass('hide-ticker1');
}
secs--;
},1000);
If anyone have a idea , how to add time please let me know
Hi you use this code below:
/// the counting date
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
The following code will start a setInterval() in which during a time window between 10:30h and 11:00h a countdown will be shown. Before 10:30h and after 11:00h different messages are shown. And after 11:00h the setInterval is cleared.
// div for output on page:
const demo=document.getElementById("demo"),
// today's date
today = new Date();
today.setHours(11);today.setMinutes(0);today.setSeconds(0);
today.intv=setInterval(checkTime,1000);
function checkTime(){
const now=new Date();
if (now>today) {
demo.textContent="Order today for tomorrow's delivery.";
clearInterval(today.intv);
}
else if (now>(today-1800000)){
let tsec=Math.floor((today-now)/1000),
sec=tsec%60,
min=(tsec-sec)/60;
demo.textContent=`${min} minutes and ${sec} seconds left if you want to order for today's delivery.`;
} else
demo.textContent="Order now for today's delivery!"
}
<p id="demo"></p>
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 have this javascript that shows remaining hours for every 24 hours and it worked well but i wanted to add a second function that show the remaining 12 hours for the day. how can i add this on my current script
(function() {
var start = new Date;
start.setHours(5, 0, 0); // military time, remaining time until 5
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
if (now > start) {
start.setDate(start.getDate() + 1);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
document.getElementById('time24').innerHTML =
hh + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('click', tick);
})();
<h2>Starts at 5am</h2>
<h4>Respawn Time every 24 hours</h4><br>
<b id="time24"></b> Until respawn<br>
<h4>Respawn Time every 12 hours</h4><br>
<b>??:??:??</b> Until respawn
edit:
For example, this script shows the remaining hours before 5am and reset (so it resets at 5am).
the second function I need is to show the remaining hours of the first 12 hours of the day and then reset.
so, if the remaining time is 24:00 for the first function, the second function should show 12:00
You can use
var hh = pad((remain / 60 / 60) % 60 % 12);
to get the hours modulus 12.
(function() {
const start = new Date;
start.setHours(5, 0, 0); // military time, remaining time until 5
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
const now = new Date;
if (now > start) {
start.setDate(start.getDate() + 1);
}
const remain = ((start - now) / 1000);
const hh = pad((remain / 60 / 60) % 60);
const hh12 = pad((remain / 60 / 60) % 60 % 12);
const mm = pad((remain / 60) % 60);
const ss = pad(remain % 60);
document.getElementById('time24').innerHTML =
hh + ":" + mm + ":" + ss;
document.getElementById('time12').innerHTML =
hh12 + ":" + mm + ":" + ss;
setTimeout(tick, 1000);
}
document.addEventListener('click', tick);
})();
<h2>Starts at 5am</h2>
<h4>Respawn Time every 24 hours</h4><br>
<b id="time24"></b> Until respawn<br>
<h4>Respawn Time every 12 hours</h4><br>
<b id="time12"></b> Until respawn
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;
}