EN
JavaScript - get number of days in specific year
0
points
In this article, we would like to show you how to get the number of days in the specific year in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const getYearDaysCount = (year) => {
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0) ? 366 : 365;
}
console.log(getYearDaysCount(2000)); // 366
console.log(getYearDaysCount(2001)); // 365
1. Check if the year is leap
In this example, we check if the specific year is leap and then return the appropriate value.
Note:
We describe in details how to check if the year is leap in the following article - JavaScript - check if the specific year is leap.
Runnable example:
// ONLINE-RUNNER:browser;
function getYearDaysCount (year) {
if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
return 366;
}
return 365;
}
console.log(getYearDaysCount(2000)); // 366
console.log(getYearDaysCount(2001)); // 365
console.log(getYearDaysCount(2002)); // 365
console.log(getYearDaysCount(2003)); // 365
console.log(getYearDaysCount(2004)); // 366
Output:
366
365
365
365
366
2. Difference between last and first day of the year
In this example, we count the difference between the last and the first day of the year to get the number of days in the specific year.
// ONLINE-RUNNER:browser;
const getYearDaysCount = (year) => {
const date1 = new Date(year, 0, 0);
const date2 = new Date(year + 1, 0, 0);
const dt = date2.getTime() - date1.getTime();
return dt / (24 * 60 * 60 * 1000);
};
// Usage example:
console.log(getYearDaysCount(2000)); // 366
console.log(getYearDaysCount(2001)); // 365
console.log(getYearDaysCount(2002)); // 365
console.log(getYearDaysCount(2003)); // 365
console.log(getYearDaysCount(2004)); // 366
Output:
366
365
365
365
366