Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  170] [ 3]  / answers: 1 / hits: 10430  / 4 Years ago, mon, june 22, 2020, 12:00:00

I am using Moment.js to retrieve the next Friday (moment().day(5).format();) which works successfully and prints 2020-06-26T13:19:01+04:00 to the console


Now I want to display a countdown timer for how long it is left to reach that certain date, the countdown includes the time left in days, hours, minutes, and seconds:


enter


How can I calculate how much time left to reach certain date in terms of days, hours, minutes, and seconds?


More From » momentjs

 Answers
4

Set a Valid End Date
First, you’ll need to set a valid end date. This should be a string in any of the formats understood by JavaScript’s Date.parse() method. For example:


const deadline = '2015-12-31';

The short format:


const deadline = '31/12/2015';

Or, the long format:


const deadline = 'December 31 2015';

Each of these formats allows you to specify an exact time and a time zone (or an offset from UTC in the case of ISO dates). For example:


const deadline = 'December 31 2015 23:59:59 GMT+0200';

Calculate the Time Remaining
The next step is to calculate the time remaining. We need to write a function that takes a string representing a given end time (as outlined above). We then calculate the difference between that time and the current time. Here’s what that looks like:


 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
};
}

First, we’re creating a variable total, to hold the remaining time until the deadline. The Date.parse() function converts a time string into a value in milliseconds. This allows us to subtract two times from each other and get the amount of time in between.


const total = Date.parse(endtime) - Date.parse(new Date());

Convert the Time to a Usable Format
Now we want to convert the milliseconds to days, hours, minutes, and seconds. Let’s use seconds as an example:


const seconds = Math.floor( (t/1000) % 60 );

Let’s break down what’s going on here.



  1. Divide milliseconds by 1000 to convert to seconds: (t/1000)

  2. Divide the total seconds by 60 and grab the remainder. You don’t want all of the seconds, just those remaining after the minutes have been counted: (t/1000) % 60

  3. Round this down to the nearest whole number. This is because you want complete seconds, not fractions of seconds: Math.floor( (t/1000) % 60 )


Repeat this logic to convert the milliseconds to minutes, hours, and days.


Output the Clock Data as a Reusable Object


With the days, hours, minutes, and seconds prepared, we’re now ready to return the data as a reusable object:


return {
total,
days,
hours,
minutes,
seconds
};

This object allows you to call your function and get any of the calculated values. Here’s an example of how you’d get the remaining minutes:


getTimeRemaining(deadline).minutes

Convenient, right?


..
Display the Clock and Stop It When It Reaches Zero


Now that we have a function that spits out the days, hours, minutes, and seconds remaining, we can build our clock. First we’ll create the following HTML element to hold our clock:


<div id="clockdiv"></div>

Then we’ll write a function that outputs the clock data inside our new div:


function initializeClock(id, endtime) {
const clock = document.getElementById(id);
const timeinterval = setInterval(() => {
const t = getTimeRemaining(endtime);
clock.innerHTML = 'days: ' + t.days + '<br>' +
'hours: '+ t.hours + '<br>' +
'minutes: ' + t.minutes + '<br>' +
'seconds: ' + t.seconds;
if (t.total <= 0) {
clearInterval(timeinterval);
}
},1000);
}

This function takes two parameters. These are the id of the element that contains our clock, and the countdown’s end time. Inside the function, we’ll declare a clock variable and use it to store a reference to our clock container div. This means we don’t have to keep querying the DOM.
Next, we’ll use setInterval to execute an anonymous function every second. This function will do the following:


Calculate the remaining time.
Output the remaining time to our div.
If the remaining time gets to zero, stop the clock.


At this point, the only remaining step is to run the clock like so:


initializeClock('clockdiv', deadline);

Congratulations! You now have a basic clock in just 18 lines of JavaScript.


Prepare Your Clock for Display
Before styling the clock, we’ll need to refine things a little.


Remove the initial delay so your clock shows up immediately.
Make the clock script more efficient so it doesn’t continuously rebuild the whole clock.
Add leading zeros as desired.


Remove the Initial Delay
In the clock, we’ve used setInterval to update the display every second. This is fine most of the time, except in the beginning when there will be a one-second delay. To remove this delay, we’ll have to update the clock once before the interval starts.


Let’s move the anonymous function that we’re passing to setInterval into its own separate function. We can name this function updateClock. Call the updateClock function once outside of setInterval, and then call it again inside setInterval. This way, the clock shows up without the delay.


In your JavaScript, replace this:


const timeinterval = setInterval(() => { ... },1000);

With this:


function updateClock(){
const t = getTimeRemaining(endtime);
clock.innerHTML = 'days: ' + t.days + '<br>' +
'hours: '+ t.hours + '<br>' +
'minutes: ' + t.minutes + '<br>' +
'seconds: ' + t.seconds;
if (t.total <= 0) {
clearInterval(timeinterval);
}
}

updateClock(); // run function once at first to avoid delay
var timeinterval = setInterval(updateClock,1000);

Avoid Continuously Rebuilding the Clock
We need to make the clock script more efficient. We’ll want to update only the numbers in the clock instead of rebuilding the entire clock every second. One way to accomplish this is to put each number inside a span tag and only update the content of those spans.


Here’s the HTML:


<div id="clockdiv">
Days: <span class="days"></span><br>
Hours: <span class="hours"></span><br>
Minutes: <span class="minutes"></span><br>
Seconds: <span class="seconds"></span>
</div>

Now let’s get a reference to those elements. Add the following code right after where the clock variable is defined


const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');

Next, we need to alter the updateClock function to update only the numbers. The new code will look like this:


function updateClock(){
const t = getTimeRemaining(endtime);

daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = t.hours;
minutesSpan.innerHTML = t.minutes;
secondsSpan.innerHTML = t.seconds;

...
}

Add Leading Zeros
Now that the clock is no longer rebuilding every second, we have one more thing to do: add leading zeros. For example, instead of having the clock show 7 seconds, it would show 07 seconds. One simple way to do this is to add a string of ‘0′ to the beginning of a number and then slice off the last two digits.


For example, to add a leading zero to the “seconds” value, you’d change this:


secondsSpan.innerHTML = t.seconds;

to this:


secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

If you’d like, you can add leading zeros to the minutes and hours as well. If you’ve come this far, congratulations! Your clock is now ready for display.


Note: You may have to click “Rerun” in the CodePen for the countdown to start.


[#3412] Thursday, June 18, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
miles

Total Points: 256
Total Questions: 111
Total Answers: 104

Location: Benin
Member since Fri, Mar 24, 2023
1 Year ago
miles questions
;