Write javascript function that calculates total number of days for a given year.
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
var jan = daysInMonth(1, 2016);
var feb = daysInMonth(2, 2016);
var maa = daysInMonth(3, 2016);
var apr = daysInMonth(4, 2016);
var mei = daysInMonth(5, 2016);
var jul = daysInMonth(6, 2016);
var jun = daysInMonth(7, 2016);
var aug = daysInMonth(8, 2016);
var sep = daysInMonth(9, 2016);
var okt = daysInMonth(10, 2016);
var nov = daysInMonth(11, 2016);
var dec = daysInMonth(12, 2016);
var dagen = jan + feb + maa + apr + mei + jul + jun + aug + sep + okt + nov + dec;
document.write('<br> Aantal dagen van jaar 2016 zijn : ' + dagen);
but i want to change the year, to 2017 but i dont want to do that 12 times.. how can i do that in 1 time
You can find the number of days using the simple leap year algorithm:
In the Gregorian calendar three criteria must be taken into account to identify leap years: The year can be evenly divided by 4; If the year can be evenly divided by 100, it is NOT a leap year, unless; The year is also evenly divisible by 400. Then it is a leap year.
function daysInYear(year) {
return ((year % 4 === 0 && year % 100 > 0) || year %400 == 0) ? 366 : 365;
}
console.log(daysInYear(2016));
console.log(daysInYear(2017));
Using loops
If it's used to teach you loops, you can use a for
loop to iterate the 12 months, and calculate the total number of days:
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
function daysInYear(year) {
var days = 0;
for(var month = 1; month <= 12; month++) {
days += daysInMonth(month, year);
}
return days;
}
console.log('2016: ', daysInYear(2016));
console.log('2017: ', daysInYear(2017));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With