Reputation: 121
I am trying to make a countdown with javascript. However, my countdown can only calculate days, hours, minutes and seconds. I also want to display years and months.
The following is my code:
<script type="text/javascript">
today = new Date();
BigDay = new Date("December 25, 2016");
msPerDay = 24 * 60 * 60 * 1000;
timeLeft = (BigDay.getTime() - today.getTime());
e_daysLeft = timeLeft / msPerDay;
daysLeft = Math.floor(e_daysLeft);
e_hrsLeft = (e_daysLeft - daysLeft) * 24;
hrsLeft = Math.floor(e_hrsLeft);
minsLeft = Math.floor((e_hrsLeft - hrsLeft) * 60);
// $("#countdown").append("There are only<BR> <H4>" + daysLeft + " days " + hrsLeft + " hours and " + minsLeft + " minutes left </H4> Until December 25th 2020<P>");
document.write(daysLeft + " days " + hrsLeft + " hours" + minsLeft + " minutes");
</script>
I would like to output:
x Years, y Months, z Days left.
Upvotes: 2
Views: 12158
Reputation: 3200
You are on the right track. Just follow the same method for dividing the days by 365 if it is over 365 and doing daysLeft modulo 365.
(Although it won't be exact, but it's a simple one and you can use it If you don't need units to be exact.)
ie
var today = new Date();
var BigDay = new Date("December 25, 2018");
var msPerDay = 24 * 60 * 60 * 1000;
var timeLeft = (BigDay.getTime() - today.getTime());
var e_daysLeft = timeLeft / msPerDay;
var daysLeft = Math.floor(e_daysLeft);
var yearsLeft = 0;
if (daysLeft > 365) {
yearsLeft = Math.floor(daysLeft / 365);
daysLeft = daysLeft % 365;
}
var e_hrsLeft = (e_daysLeft - daysLeft) * 24;
var hrsLeft = Math.floor(e_hrsLeft);
var minsLeft = Math.floor((e_hrsLeft - hrsLeft) * 60);
document.write(yearsLeft + " years " + daysLeft + " days " + hrsLeft + " hours " + minsLeft + " minutes");
Upvotes: 4
Reputation: 3617
Months actually contain a varying number of days. Some are 30 days, others are 31. February is even worse, containing 28 days with an additional day every 4 years (leap years). Displaying the number of 'Years' would be less onerous, but there are still leap years to contend with.
So there isn't any simple way to calculate them exactly.
For a code that demonstrates calculat Years, Months and Weeks,
check this page:
http://blog.refoua.me/post/day-counter/?lang=en
Although it is not a simple one, it works and calculates units as exactly as it can.
Upvotes: 2