This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 2 years ago.
So, I am a novice in Javascript and I am wondering if someone can help me with this. I believe this question is really really easy for most. Well, this is a countdown timer with select options to set up the time. It is working well. The problem is that, when the countdown starts, I want the single digit numbers to show the number zero first. Basically, I want the numbers for HH:MM:SS to be 2 digits. For example, 00:01:59 and not 0:1:59. I believe it has something to do with padString or something (I could be wrong), but my proficiency is still no that advanced.
Note: I would highly appreciate it if we can come up with a Vanilla Javascript solution and not JQuery simply because I want to use this offline and without any online dependencies. Thank you in advance.
Javascript
<script>
var hours = 0;
var minutes = 0;
var seconds = 0;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = displayHours + ":" +
displayMinutes + ":" + displaySeconds;
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});
</script>
You could use ('0' + myValue).substr(-2) to fix the length with 2 characters. In this case '01' would be stay as '01' and '012' will be '12' because the -2 will cut the string from the end. Then your code will be:
var hours = 00;
var minutes = 00;
var seconds = 00;
var interval = null;
document.getElementById('hours').addEventListener('change', e => {
hours = +e.target.value;
});
document.getElementById('minutes').addEventListener('change', e => {
minutes = +e.target.value;
});
document.getElementById('seconds').addEventListener('change', e => {
seconds = +e.target.value;
});
document.getElementById('startTimer').addEventListener('click', () => {
var timeInSeconds = (hours * 60 * 60) +
(minutes * 60) +
seconds;
const audio = new Audio("audioURL.mp3");
var displayTime = () => {
var displayHours = Math.floor(timeInSeconds / (60 * 60));
var remainder = timeInSeconds - (displayHours * 60 * 60);
var displayMinutes = Math.floor(remainder / 60);
var displaySeconds = remainder - (displayMinutes * 60);
document.getElementById("timer").innerHTML = ('0' + displayHours).substr(-2) + ":" +
('0' + displayMinutes).substr(-2) + ":" + ('0' + displaySeconds).substr(-2);
};
interval = setInterval(() => {
displayTime();
timeInSeconds -= 1;
if (timeInSeconds < 0) {
clearInterval(interval);
audio.play();
}
}, 1000);
});
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 am struggling to make this code to work with localStorage so if anyone can help me that would be amazing. How do I implement a localStorage in order to save the countdown when refreshing the page?
var hour = 5 * 3600;
var minute = 5 * 60;
var deadline = hour + minute;
function formatTime(seconds) {
var hide = false;
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60;
return h + m;
}
var counter = setInterval(timer, 1000);
function timer() {
deadline--;
if (deadline < 0) {
return clearInterval(counter);
}
$('#deadline').html(formatTime(deadline));
}
Store the value in the localStorage everytime the value gets decreased.
When you reload the page, check if the stored time exists, if yes store it in your deadline variable, otherwise let the deadline be the initial one.
var hour = 5 * 3600;
var minute = 5 * 60;
var deadline = hour + minute;
function formatTime(seconds) {
var hide = false;
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60;
console.log(h)
console.log(m)
return h + m;
}
var counter;
var storedTime = localStorage.getItem('deadline')
if (storedTime) {
deadline = Number(storedTime)
}
counter = setInterval(timer, 1000);
function timer() {
--deadline;
localStorage.setItem('time', deadline);
if (deadline < 0) {
return clearInterval(counter);
}
$('#deadline').html(formatTime(deadline));
}
I just can't figure why this doesn't work for some odd values.
For example when trying to convert 22.68 to hours and minutes the output is 22:40.800000000000004 (Seconds shouldn't even appear)
if (str_HR_PER_WEEK.indexOf('.') > -1)
{
var str_HR_PER_WEEK_hrs = str_HR_PER_WEEK.substring(0 , str_HR_PER_WEEK.indexOf('.'));
var str_HR_PER_WEEK_mins = str_HR_PER_WEEK.substring(str_HR_PER_WEEK.indexOf('.') + 1);
var float_HR_PER_WEEK_mins = parseFloat("0." + (str_HR_PER_WEEK_mins), 10);
var float_HR_PER_WEEK_mins_actual = float_HR_PER_WEEK_mins * 60;
float_HR_PER_WEEK_mins_actual = float_HR_PER_WEEK_mins_actual.toString();
tables.CURRENT_EMPLOYEES.HOURS_PER_WEEK.value = getTwoDigitTime(str_HR_PER_WEEK_hrs) + ":" + getTwoDigitTime(float_HR_PER_WEEK_mins_actual);
}
else
{
tables.CURRENT_EMPLOYEES.HOURS_PER_WEEK.value = str_HR_PER_WEEK;
}
You have to ways to achieve that,
one, do the calculations yourself:
var decimalTimeString = "1.6578";
var decimalTime = parseFloat(decimalTimeString);
decimalTime = decimalTime * 60 * 60;
var hours = Math.floor((decimalTime / (60 * 60)));
decimalTime = decimalTime - (hours * 60 * 60);
var minutes = Math.floor((decimalTime / 60));
decimalTime = decimalTime - (minutes * 60);
var seconds = Math.round(decimalTime);
if(hours < 10)
{
hours = "0" + hours;
}
if(minutes < 10)
{
minutes = "0" + minutes;
}
if(seconds < 10)
{
seconds = "0" + seconds;
}
alert("" + hours + ":" + minutes + ":" + seconds);
Two, use built in function to convert to string and then to hh:mm:
var decimalTimeString = "1.6578";
var n = new Date(0,0);
n.setSeconds(+decimalTimeString * 60 * 60);
n.setMinutes(+decimalTimeString * 60);
var result = n.toTimeString().slice(0, 5);
document.write(result);
I've got a neat function to do just that:
function hoursToHHMM(hours) {
var h = String(Math.trunc(hours)).padStart(2, '0');
var m = String(Math.abs(Math.round((hours - h) * 60))).padStart(2, '0');
return h + ':' + m;
}
It handles negative values as a bonus.
Usage is trivial:
var hours = -7.33333;
console.log(hoursToHHMM(hours));
Results in: -07:20
You can play with it here: https://jsfiddle.net/r150c2me/
How to parse a given amount of milliseconds (e.g. 125230.41294642858) into a time format like: minutes:seconds?
var ms = 125230.41294642858,
min = 0|(ms/1000/60),
sec = 0|(ms/1000) % 60;
alert(min + ':' + sec);
Try the following
var num = Number(theTextValue);
var seconds = Math.floor(num / 1000);
var minutes = Math.floor(seconds / 60);
var seconds = seconds - (minutes * 60);
var format = minutes + ':' + seconds
Number.prototype.toTime = function(){
var self = this/1000;
var min = (self) << 0;
var sec = (self*60) % 60;
if (sec == 0) sec = '00';
return min + ':' + sec
};
var ms = (new Number('250')).toTime();
console.log(ms);
=> '0:15'
var ms = (new Number('10500')).toTime();
console.log(ms);
=> '10:30'
Even though moment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function getFormattedMs(ms) {
var duration = moment.duration(ms);
return moment.utc(duration.asMilliseconds()).format("mm:ss");
}
This workaround in moment was introduced in this Issue.
Hi I am having a hard time making this countdown work for me. I am trying to make it count down to every sunday at 11:15am since that is when our church service starts. Can anyone pleaes help me? I have the code here.
function croAnim(){
// IF THERE'S A COUNTDOWN
if ($('ul.cro_timervalue').length !== 0) {
// GET ALL THE INSTANCES OF THE TIMER
$('ul.cro_timervalue').each(function() {
var $this = $(this),
timesets = $this.data('cro-countdownvalue'),
now = new Date(),
tset = Math.floor(now / 1000),
counter1 = timesets - tset;
// CALCULATE SECONDS
var seconds1 = Math.floor(counter1 % 60);
seconds1 = (seconds1 < 10 && seconds1 >= 0) ? '0'+ seconds1 : seconds1;
// CALCULATE MINUTES
counter1 =counter1/60;
var minutes1 =Math.floor(counter1 % 60);
minutes1 = (minutes1 < 10 && minutes1 >= 0) ? '0'+ minutes1 : minutes1;
// CALCULATE HOURS
counter1=counter1/60;
var hours1=Math.floor(counter1 % 24);
hours1 = (hours1 < 10 && hours1 >= 0) ? '0'+ hours1 : hours1;
// CALCULATE DAYS
counter1 =counter1/24;
var days1 =Math.floor(counter1);
days1 = (days1 < 10 && days1 >= 0) ? '0'+ days1 : days1;
// ADD THE VALUES TO THE CORRECT DIVS
$this.find('span.secondnumber').html(seconds1);
$this.find('span.minutenumber').html(minutes1);
$this.find('span.hournumber').html(hours1);
$this.find('span.daynumber').html(days1);
});
}
}
// CREATE A INTERVAL FOR THE TIMER
croInit = setInterval(croAnim, 100);
I answered a similar question about a week or so ago. I have a really simple countdown function already written. The trick is to modify it to get the next Sunday # 11:15 am, which I've written a function for.
var getNextSunday = function () {
var today = new Date(),
day = today.getDay(), // 1 for Mon, 2 for Tue, 3 for Wed, etc.
delta = 7 - day;
var sunday = new Date(today.getTime() + (delta * 24 * 3600 * 1000));
sunday.setHours(11);
sunday.setMinutes(15);
sunday.setSeconds(0);
return sunday;
}
var t = getNextSunday(),
p = document.getElementById("time"),
timer;
var u = function () {
var delta = t - new Date(),
d = delta / (24 * 3600 * 1000) | 0,
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0,
m = (delta %= 3600 * 1000) / (60 * 1000) | 0,
s = (delta %= 60 * 1000) / 1000 | 0;
if (delta < 0) {
clearInterval(timer);
p.innerHTML = "timer's finished!";
} else {
p.innerHTML = d + "d " + h + "h " + m + "m " + s + "s";
}
}
timer = setInterval(u, 1000);
<h1 id="time"></h1>
This should be easy enough to adapt to fit your website's needs. The only tricky part might be my use of
h = (delta %= 24 * 3600 * 1000) / (3600 * 1000) | 0
delta %= ... returns delta, after performing the %=. This was just to save characters. If you don't like this, you can just separate the delta %= ... part:
delta %= 24 * 3600 * 1000;
h = delta / (3600 * 1000) | 0;
// ... do the same for the rest
This object uses a few semi-advanced javascript ideas (closures and * IIFE*) so hopefully it is easy-ish to understand. If you have any questions feel free to leave a comment.
var churchtime = (function (){
// Total seconds passed in the week by sunday 11:15am
var magic_number = 558900;
var now;
var rawtime = function (){
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay()-1)*24)+now.getHours())*60)+now.getMinutes())*60)+now.getSeconds());
};
//closure
return {
raw_countdown : function (){
return Math.abs(rawtime()-magic_number);
},
countdown : function(){
var time = Math.abs(rawtime()-magic_number)
var seconds = time % 60, time = (time - seconds)/60;
var minutes = time % 60, time = (time - minutes)/60;
var hours = time % 24, time = (time - hours)/24;
var days = time;
return [days,hours,minutes,seconds];
}
}
})(558900); //<- Total seconds passed in the week by sunday 11:15am
churchtime.raw_countdown()// returns the raw number of seconds until church
churchtime.countdown() // returns an array of time until church [days,hours,minutes,seconds]
Once you have an object like churchtime, it should be super easy to implement.
For example:
var churchtime = (function(magic_number) {
var now;
var rawtime = function() {
//updates now with the current date and time
now = new Date()
//Converts now into pure seconds
return (((((((now.getDay() - 1) * 24) + now.getHours()) * 60) + now.getMinutes()) * 60) + now.getSeconds());
};
//closure
return {
raw_countdown: function() {
return Math.abs(rawtime() - magic_number);
},
countdown: function() {
var time = Math.abs(rawtime() - magic_number)
var seconds = time % 60,
time = (time - seconds) / 60;
var minutes = time % 60,
time = (time - minutes) / 60;
var hours = time % 24,
time = (time - hours) / 24;
var days = time;
return [days, hours, minutes, seconds];
}
}
})(); //<- IIFE
AutoUpdate = function AutoUpdate() {
var time = churchtime.countdown();
document.getElementById("day").innerHTML = time[0];
document.getElementById("hour").innerHTML = time[1];
document.getElementById("min").innerHTML = time[2];
document.getElementById("sec").innerHTML = time[3];
setTimeout(AutoUpdate, 900); //Calls it's self again after .9 seconds
}(); //<- IIFE
<h1>Day:<span id="day"></span> Hour:<span id="hour"></span>
Minute:<span id="min"></span> second: <span id="sec"></span></h1>