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:
xxxxxxxxxx
1
const getYearDaysCount = (year) => {
2
return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0) ? 366 : 365;
3
}
4
5
console.log(getYearDaysCount(2000)); // 366
6
console.log(getYearDaysCount(2001)); // 365
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:
xxxxxxxxxx
1
function getYearDaysCount (year) {
2
if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
3
return 366;
4
}
5
return 365;
6
}
7
8
console.log(getYearDaysCount(2000)); // 366
9
console.log(getYearDaysCount(2001)); // 365
10
console.log(getYearDaysCount(2002)); // 365
11
console.log(getYearDaysCount(2003)); // 365
12
console.log(getYearDaysCount(2004)); // 366
Output:
xxxxxxxxxx
1
366
2
365
3
365
4
365
5
366
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.
xxxxxxxxxx
1
const getYearDaysCount = (year) => {
2
const date1 = new Date(year, 0, 0);
3
const date2 = new Date(year + 1, 0, 0);
4
const dt = date2.getTime() - date1.getTime();
5
return dt / (24 * 60 * 60 * 1000);
6
};
7
8
// Usage example:
9
console.log(getYearDaysCount(2000)); // 366
10
console.log(getYearDaysCount(2001)); // 365
11
console.log(getYearDaysCount(2002)); // 365
12
console.log(getYearDaysCount(2003)); // 365
13
console.log(getYearDaysCount(2004)); // 366
Output:
xxxxxxxxxx
1
366
2
365
3
365
4
365
5
366