I'm trying to get the closest date from now from an array and use it in the countdown timer along with that objects associated properties like event.
I've managed to get this far, from looking around on the web, but my code only pulls the last entry from the array not the closest date.
If anyone can help or push me in the right direction that would be great.
<p id="demo"></p>
<p id="celebration"></p>
<script>
// Get today's date and time
var now = new Date().getTime();
var data = [
{
date: "04/10/2021",
event: "event 1",
},
{
date: "08/15/2022",
event: "event 2",
},
{
date: "09/15/2021",
event: "event 3",
},
{
date: "01/12/2025",
event: "event 4",
},
];
var closest = data.reduce((a, b) => (a.date - now < b.date - now ? a : b));
console.log(closest.date);
// Set the date we're counting down to
var countDownDate = new Date(closest.date);
// Update the count down every 1 second
var x = setInterval(function () {
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor(
(distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
);
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML =
days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
document.getElementById("celebration").innerHTML = closest.event;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
document.getElementById("celebration").innerHTML = "None";
}
}, 1000);
</script>
dateare strings. To treaat them as dates you'll need to first parse themexpireddate. Do you still want that or the next one which is not expired?