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)
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>
Related
Hey I try to run the timer always until 24 o'clock but it always runs 24 when the page is loaded. I do not understand how I can calculate that the timer always shows the correct time until 24 o'clock can someone help me?
const countToDate = new Date().setHours(new Date().getHours() + 24)
let previousTimeBetweenDates
setInterval(() => {
const currentDate = new Date()
const timeBetweenDates = Math.ceil((countToDate - currentDate) / 1000)
flipAllCards(timeBetweenDates)
previousTimeBetweenDates = timeBetweenDates
}, 250)
function flipAllCards(time) {
const seconds = time % 60
const minutes = Math.floor(time / 60) % 60
const hours = Math.floor(time / 3600)
flip(document.querySelector("[data-hours-tens]"), Math.floor(hours / 10))
flip(document.querySelector("[data-hours-ones]"), hours % 10)
flip(document.querySelector("[data-minutes-tens]"), Math.floor(minutes / 10))
flip(document.querySelector("[data-minutes-ones]"), minutes % 10)
flip(document.querySelector("[data-seconds-tens]"), Math.floor(seconds / 10))
flip(document.querySelector("[data-seconds-ones]"), seconds % 10)
}
function flip(flipCard, newNumber) {
const topHalf = flipCard.querySelector(".top")
const startNumber = parseInt(topHalf.textContent)
if (newNumber === startNumber) return
const bottomHalf = flipCard.querySelector(".bottom")
const topFlip = document.createElement("div")
topFlip.classList.add("top-flip")
const bottomFlip = document.createElement("div")
bottomFlip.classList.add("bottom-flip")
top.textContent = startNumber
bottomHalf.textContent = startNumber
topFlip.textContent = startNumber
bottomFlip.textContent = newNumber
topFlip.addEventListener("animationstart", e => {
topHalf.textContent = newNumber
})
topFlip.addEventListener("animationend", e => {
topFlip.remove()
})
bottomFlip.addEventListener("animationend", e => {
bottomHalf.textContent = newNumber
bottomFlip.remove()
})
flipCard.append(topFlip, bottomFlip)
}
I made a timer for a project in school (I am still in school yes and I do not have JavaScript as a lesson that we get this semester) in JavaScript and it continues after the 0. I got some help from a teacher but I can't reach him with the pandemic and stuff.
This is the code that I wrote and what happens is that when it reaches the date that I put in it goes into -0 -0 -0 -01 and continues from there.
const countdown = () => {
let countDate = new Date('Febuary 9, 2022 00:00:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
setInterval(countdown, 1000);
setInterval returns a value which you can pass to clearInterval to stop the interval from running. Store that value in a variable, for example:
let countInterval = 0;
const countdown = () => {
//...
};
countInterval = setInterval(countdown, 1000);
Then within countdown you can check if you want to clear that interval. For example, if you want to clear it when gap <= 0 you would perform that logic:
if (gap <= 0) {
clearInterval(countInterval);
return;
}
This would stop the interval from running when that condition is eventually met.
Example:
let countInterval = 0;
const countdown = () => {
let countDate = new Date('January 11, 2022 13:35:00').getTime();
let now = new Date().getTime();
let gap = countDate - now;
if (gap <= 0) {
clearInterval(countInterval);
return;
}
let second = 1000;
let minute = second * 60;
let hour = minute * 60;
let day = hour * 24;
let textDay = Math.floor(gap / day);
let textHour = Math.floor((gap % day) / hour);
let textMinute = Math.floor((gap % hour) / minute);
let textSecond = Math.floor((gap % minute) / second);
document.querySelector('.day').innerText = textDay;
document.querySelector('.hour').innerText = textHour;
document.querySelector('.minute').innerText = textMinute;
document.querySelector('.second').innerText = textSecond;
};
countInterval = setInterval(countdown, 1000);
<div class="day"></div>
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
I am trying to create a countdown timer for every Monday, Wednesday and Friday at 2000 hours in JavaScript.
Countdown is working till 2000 hours but after that its not working and also I can't figure out how to switch week i.e. Friday to switch next Monday as there are 3 days count and normal in week there are two days and also I don't want to show days.
I want to convert days into hours and my UI is like 47h 59m 50s this.
I would be grateful if anyone can figure out how to create this countdown.
const gameCountdown = setInterval(function() {
var gameDay;
var currentDateTime = new Date();
var currentDay = currentDateTime.getDay();
var currentTime = currentDateTime.getTime();
var gameTime = new Date(currentDateTime.getFullYear(), currentDateTime.getMonth(), currentDateTime.getDate(), 20, 0, 0); // current day 8pm
var gameDay = (currentDay % 2 === 0) ? currentDay + 1 : currentDay;
if ((currentDay === gameDay) && (gameTime.getHours() >= 20)) {
gameTime = currentDateTime.setDate(currentDateTime.getDate() + 2);
}
var countdownTime = gameTime.getTime();
var difference = parseInt((countdownTime - currentTime));
if (difference > 0) {
var hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
var mins = Math.floor((difference / (1000 * 60)) % 60);
var sec = Math.floor((difference / 1000) % 60);
document.querySelector('#hours').innerHTML = hours + 'h';
document.querySelector('#min').innerHTML = mins + 'm';
document.querySelector('#sec').innerHTML = sec + 's';
} else {
var hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
var mins = Math.floor((difference / (1000 * 60)) % 60);
var sec = Math.floor((difference / 1000) % 60);
document.querySelector('#hours').innerHTML = hours + 'h';
document.querySelector('#min').innerHTML = mins + 'm';
document.querySelector('#sec').innerHTML = sec + 's';
}
}, 1000);
<span id="hours"></span>
<span id="min"></span>
<span id="sec"></span>
Does this work for you?
const getGameTime = (currentTime) => {
let gameDate = new Date(currentTime)
let offset = 0;
if (gameDate.getHours() >= 20) {
offset += gameDay === 5 ? 3 : // Friday after 20:00
1; // any other day
}
gameDate.setDate(gameDate.getDate() + offset);
let gameDay = gameDate.getDay();
offset = 0;
if (gameDay === 0) offset += 1; // Sunday
else if (gameDay === 2 || gameDay === 4) offset += 1; // Tuesday or Thursday
else if (gameDay === 6) offset += 2; // Saturday
gameDate.setDate(gameDate.getDate() + offset);
gameDate.setHours(20, 0, 0);
return gameDate.getTime();
}
const gameCountdown = setInterval(function() {
var gameDay;
var currentDateTime = new Date();
var currentDay = currentDateTime.getDay();
var currentTime = currentDateTime.getTime();
var countdownTime = getGameTime(currentTime);
var difference = parseInt((countdownTime - currentTime));
var hours = Math.floor((difference / (1000 * 60 * 60)));
var mins = Math.floor((difference / (1000 * 60)) % 60);
var sec = Math.floor((difference / 1000) % 60);
document.querySelector('#hours').innerHTML = hours + 'h';
document.querySelector('#min').innerHTML = mins + 'm';
document.querySelector('#sec').innerHTML = sec + 's';
}, 1000);
<span id="hours"></span>
<span id="min"></span>
<span id="sec"></span>
I want to calculate the difference beetween two dates in Javascript in months, weeks, days, hours, minutes and seconds.
Problem:
Weeks and days aren't calculated properly.
I already tried to change .get...() into .getUTC...() but the difference was calculated wrong either.
var date = new Date("{% if holiday.is_now %}{{ holiday.end_date.isoformat }}{% else %}{{ holiday.end_date.isoformat }}{% endif %}");
function calcDate(a, b) {
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDay(), a.getHours(), a.getMinutes(), a.getSeconds());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDay(), b.getHours(), b.getMinutes(), b.getSeconds());
return (utc2 - utc1) / 1000;
}
function convertDate(seconds){
var sec = Math.floor(seconds % 60);
var min = Math.floor(seconds / 60 % 60);
var hour = Math.floor(seconds / 60 / 60 % 24);
var diff = seconds / 60 / 60 / 24;
var months = Math.floor(diff / 30);
var weeks = Math.floor(diff / 7 % (30 / 7));
var days = Math.floor(diff % 7);
console.log(days);
return [months, weeks, days, hour, min, sec]
}
function add_countdown(sec){
$.each(convertDate(sec), function(i, element){
var selected = $("footer .countdown .counter#_counter_date_" + i);
selected.find("h1").text(element);
singular_pluralize(selected.find("p"), element);
})
}
function singular_pluralize(element, integer){
integer > 1 || integer == 0 ? element.text(element.attr("data-word-plural")) : element.text(element.attr("data-word-singular"));
}
var interval;
$("footer table td.a").on("click mouseup", function(){
clearInterval(interval);
date = new Date($(this).attr("data-date"));
$("footer #_foter_big_countdown_to_what").text("zu den " + $(this).attr("data-name").replace(/ /g, ''));
set_interval();
})
function set_interval(){
add_countdown(calcDate(new Date(), date));
interval = window.setInterval(function(){
var calc = calcDate(new Date(), date);
if (calc == 0)
holiday_begin();
else
add_countdown(calc);
}, 900);
}
function holiday_begin(){
$("footer .counter, footer .part#_footer_select_holiday").remove();
$("footer .darken h1._footer_big_countdown").html("Fröhliche Ferien!");
}
set_interval();
EDIT:
I found the solution. I had to use Math.round and I had to change a little bit:
function convertDate(seconds){
var sec = Math.round(seconds % 60);
var min = Math.round(seconds / 60 % 60);
var hour = Math.round(seconds / 60 / 60 % 24);
var diff = seconds / 60 / 60 / 24;
var months = Math.round(diff / 30);
var days = Math.round(diff % 30);
var weeks = Math.round(months / 4.3);
return [months, weeks, days, hour, min, sec]
}
Hope you are all well,
I've been struggling to find a way to display the amount of time that has passed since a specific date in years, months, weeks and days. The closest i have found, is this below but i can quite work out how to get it to display the years and months.
Any tips would be greatly appreciated.
Thanks
window.onload = function() {
doTime('jan,01,2017,00:00:01');
}
function doTime(then) {
now = new Date();
then = new Date(then);
difference = (now - then);
days = Math.floor(difference / (60 * 60 * 1000 * 24) * 1);
hours = Math.floor((difference % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
mins = Math.floor(((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
secs = Math.floor((((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);
document.getElementById('timer').firstChild.nodeValue =
+days + ' days ' + hours + ' hours ' + mins + ' minutes ' + secs + ' seconds';
clearTimeout(doTime.to);
doTime.to = setTimeout(function() {
doTime(then);
}, 1000);
}
<div id="timer"> </div>
—
thanks for the suggestion of the previous post, sadly i have tried that and i can only get it to work the difference between two actual dates, i cant get it to automatically make the end date now so it counts up automatically as time goes on.
—
i have done some more fiddling and managed to get to this, being new to js, would you guys say this is pretty close? thanks
var startDateTime = new Date(2012,5,24,09,43,0,0); // YYYY (M-1) D H m s
(start time and date from DB)
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer;
function updateClock() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000)
var years = Math.floor(diff/(12*4.3479*7*24*60*60));
diff = diff-(years*12*4.3479*7*24*60*60)
var months = Math.floor(diff/(4.3479*7*24*60*60));
diff = diff-(months*4.3479*7*24*60*60)
var weeks = Math.floor(diff/(7*24*60*60));
diff = diff-(weeks*7*24*60*60)
var days = Math.floor(diff/(24*60*60));
diff = diff-(days*24*60*60);
var hours = Math.floor(diff/(60*60));
diff = diff-(hours*60*60);
var mins = Math.floor(diff/(60));
diff = diff-(mins*60);
var secs = diff;
document.getElementById("time-elapsed").innerHTML = years+" years,
"+months+" months, " +weeks+" weeks, " +days+" days, "+hours+" hours and
"+mins+" minutes,";
}
setInterval(updateClock, 1000);
<div id="time-elapsed"></div>
Simple, approximate difference
function calculateDifference(thenString) {
const second = 1000
const minute = 60 * second
const hour = 60 * minute
const day = 24 * hour
const month = 30 * day // approximately
const year = 365 * day // approximately
const now = new Date();
const then = new Date(thenString);
let difference = (now - then);
const time = [{ year }, { month }, { day }, { hour }, { minute }, { second }].map((item, i, a) => {
const [[unitName, unit]] = Object.entries(item)
const units = difference / unit | 0
difference -= unit * units
const maybePlural = units === 1 ? "" : "s"
return units > 0 ? units + " " + unitName + maybePlural : ""
}).filter(x => x)
const formattedTime = time.length > 1 ? [...time.slice(0, -1), "and", time.slice(-1)].join(" ") : time[1]
return formattedTime
}
function displayDifference() {
displayBox.textContent = calculateDifference(dateInput.value + ", " + timeInput.value)
}
const dateInput = document.querySelector(".date")
const timeInput = document.querySelector(".time")
const displayBox = document.querySelector(".js-display-difference")
dateInput.addEventListener("change", displayDifference)
timeInput.addEventListener("change", displayDifference)
displayDifference()
setInterval(displayDifference, 1000)
<h3>
since
<input class="date" type="date" value="2017-01-01"/>
<input class="time" type="time" value="00:00"/>
elapsed
<span class="js-display-difference"></span>
</h3>
Precise difference with momentjs and precise range plugin
function calculateDifference(thenString) {
var m1 = moment(Date.now())
var m2 = moment(new Date(thenString))
var diff = moment.preciseDiff(m1, m2)
return diff
}
function displayDifference() {
displayBox.textContent = calculateDifference(dateInput.value + ", " + timeInput.value)
}
const dateInput = document.querySelector(".date")
const timeInput = document.querySelector(".time")
const displayBox = document.querySelector(".js-display-difference")
dateInput.addEventListener("change", displayDifference)
timeInput.addEventListener("change", displayDifference)
displayDifference()
setInterval(displayDifference, 1000)
<script src="https://unpkg.com/moment#2.18.1"></script>
<script src="https://unpkg.com/moment-precise-range-plugin#1.2.3"></script>
<h3>
since
<input class="date" type="date" value="2017-01-01"/>
<input class="time" type="time" value="00:00"/>
elapsed
<span class="js-display-difference"></span>
I'm not an IT expert so there is probably a better way, but what I have done seems to work. An example can be seen here: Date difference in action
My approach was not to workout the difference in days from the first date but to work out the day position in the 'to date' from the day position in the 'from date'. i.e. on my 60th birthday there had been 15 leap years since I was born, but those days aren't counted. I am 60 years old not 60 years and 15 days.
And just to prove I'm not an IT expert I am unable to post the code but you can view the source code in the example.
BTW I only use chrome / edge so it's not been tested on other platforms.