How to specify how many days during a month during a certain year?

How to specify how many days per month for a particular year in JavaScript?

As we know 30 days - September, April, June and November. Everyone else has 31, except February, which has 28 days clear, and 29 in each leap year.

I will need a leap year count. Do you know any native way to love .. or maybe a library .. could you offer it?

+6
source share
4 answers

try it

function daysInMonth(m, y) { m=m-1; //month is zero based... return 32 - new Date(y, m, 32).getDate(); } 

using:

>> daysInMonth(2,2000) //29

+9
source

This will also work if Jan=1, Feb=2 ... Dec=12

 function daysInMonth(month,year) { return new Date(year, month, 0).getDate(); } 

Fiddle

+3
source

You could, of course, just write a function based on what you already know, combined with logic for leap years:

 // m is the month (January = 0, February = 1, ...) // y is the year function daysInMonth(m, y) { return m === 1 && (!(y % 4) && ((y % 100) || !(y % 400))) ? 29 : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m]; } 

Years divisible by 4 but not divisible by 100, except when they are divided by 400, are leap years.

+3
source

There are probably native ways to find out, but I am pleased to know that the leap year algorithm is actually not so difficult to implement myself:

 function isLeapYear(year) { if (year % 400 === 0) { return true; } else if (year % 100 === 0) { return false; } else if (year % 4 === 0) { return true; } return false; } 
0
source

Source: https://habr.com/ru/post/950193/


All Articles