From fd238b81275e13e8926d529e2ea11e033d4ba295 Mon Sep 17 00:00:00 2001 From: Rohit12012007 <rohitsasikumar3@gmail.com> Date: Sat, 19 Oct 2024 10:10:49 +0530 Subject: [PATCH] Update script.js clear code --- Count-Down-To-New-Year/script.js | 50 +++++++++++++++++--------------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/Count-Down-To-New-Year/script.js b/Count-Down-To-New-Year/script.js index 3e91fb202..ffbe2e465 100644 --- a/Count-Down-To-New-Year/script.js +++ b/Count-Down-To-New-Year/script.js @@ -1,33 +1,37 @@ -const dayEl = document.getElementById("days") +const dayEl = document.getElementById("days"); const hourEl = document.getElementById("hours"); const minuteEl = document.getElementById("minutes"); const secondEl = document.getElementById("seconds"); -const d = 1 -const m = "jan" -var y = 2024 function countdown() { - const newYear = d + m + y; - const newYearDate = new Date(newYear); + // Get the current date const currentDate = new Date(); + + // Calculate the next New Year's date (Jan 1 of the next year) + const nextYear = currentDate.getFullYear() + 1; + const newYearDate = new Date(`January 1, ${nextYear} 00:00:00`); + + // Get the total number of seconds between now and New Year's const totalSeconds = (newYearDate - currentDate) / 1000; + + // Convert total seconds into days, hours, minutes, and seconds const days = Math.floor(totalSeconds / 3600 / 24); - const hours = Math.floor(totalSeconds / 3600) % 24; - const minutes = Math.floor(totalSeconds / 60) % 60; - const seconds = Math.floor(totalSeconds) % 60; - - dayEl.innerHTML = formateTime(days); - hourEl.innerHTML = formateTime(hours); - minuteEl.innerHTML = formateTime(minutes); - secondEl.innerHTML = formateTime(seconds); - - if(days === 0 && hours === 0 && minutes === 0 && seconds === 0){ - y+=1; - } - + const hours = Math.floor((totalSeconds / 3600) % 24); + const minutes = Math.floor((totalSeconds / 60) % 60); + const seconds = Math.floor(totalSeconds % 60); + + // Display the countdown + dayEl.innerHTML = formatTime(days); + hourEl.innerHTML = formatTime(hours); + minuteEl.innerHTML = formatTime(minutes); + secondEl.innerHTML = formatTime(seconds); } -function formateTime(time){ - return time < 10 ? `0${time}` : time;} - + +// Helper function to format time (adds a leading zero if less than 10) +function formatTime(time) { + return time < 10 ? `0${time}` : time; +} + +// Run the countdown immediately and update it every second countdown(); -setInterval(countdown, 1000); \ No newline at end of file +setInterval(countdown, 1000);