Reputation: 895
I am trying to create a function that will countdown the days from today's date to a specific given date, using javascript or jquery.
This is what I have now and it works pretty fine, but how can I make it so it will run every year?
function daysDifference($startDate, $endDate) {
oneDay = 24*60*60*1000;
return Math.ceil(($endDate.getTime() - $startDate.getTime()) / oneDay);
}
$today = new Date();
$endDate = new Date(2019, 12, 31);
document.getElementById("counter").innerHTML = + daysDifference($today, $endDate) + ' days left for the new Year';
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="counter"></div>
Upvotes: 0
Views: 112
Reputation: 484
It is very simple, you just need to change your dates to:
$today = new Date();
$endDate = new Date($today.getFullYear(), 11, 31);
Edit: After the current day is past, but still on the year, you can do this to keep the count going:
if($today > $endDate) {
$endDate = new Date($today.getFullYear() + 1, 11, 31);
}
This should keep it going forever.
Upvotes: 2