0

I have a countdown timer for next 25 years. how can I display years in this timer. currently instead of year days are showing. I need to display the years also. please help . enter image description here

please find the code i have used "code"

enter code here

 let daysItem = document.querySelector("#days");
 let hoursItem = document.querySelector("#hours");
 let minItem = document.querySelector("#min");
 let secItem = document.querySelector("#sec");

 let countDown = () => {
 let futureDate = new Date("17 august 2022 9:59:59");
 let currentDate = new Date();
 let myDate = futureDate - currentDate;
 //console.log(myDate);

 let days = Math.floor(myDate / 1000 / 60 / 60 / 24);

 let hours = Math.floor(myDate / 1000 / 60 / 60) % 24;

 let min = Math.floor(myDate / 1000 / 60) % 60;

 let sec = Math.floor(myDate / 1000) % 60;

 daysItem.innerHTML = days;
 hoursItem.innerHTML = hours;
 minItem.innerHTML = min;
 secItem.innerHTML = sec;
}

countDown()

setInterval(countDown, 1000)

1 Answer 1

1

You need to make calculation with getFullYear() from current date to futur date.

let yearsItem = document.querySelector("#years");
let daysItem = document.querySelector("#days");
let hoursItem = document.querySelector("#hours");
let minItem = document.querySelector("#min");
let secItem = document.querySelector("#sec");

let countDown = () => {
 let futureDate = new Date("17 august 2047 9:59:59");
 let currentDate = new Date();
 let myDate = futureDate - currentDate;
 //console.log(myDate);

 let years = futureDate.getFullYear() - currentDate.getFullYear(); 
 
 let days = Math.floor(myDate / 1000 / 60 / 60 / 24);

 let hours = Math.floor(myDate / 1000 / 60 / 60) % 24;

 let min = Math.floor(myDate / 1000 / 60) % 60;

 let sec = Math.floor(myDate / 1000) % 60;
 
 yearsItem.innerHTML = years;
 daysItem.innerHTML = days;
 hoursItem.innerHTML = hours;
 minItem.innerHTML = min;
 secItem.innerHTML = sec;
}

countDown()

setInterval(countDown, 1000)
div { display:inline-block; padding:5px; background:#000; color:#fff }
Years <div id="years"></div>
Days <div id="days"></div>
Hours <div id="hours"></div>
Min <div id="min"></div>
Sec <div id="sec"></div>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks . but here date is wrong. 23 YEARS- 295 DAYS, 10 hours, 10 min, 3 sec like that i need
You where asking for years, that's what i did. @sanishmashylendran
Note that Stackoverflow is not free coding website. We help if you get stuck in your codes developments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.