preface
You receive a request that requires you to enter the year and month and return the date of the last day of the month. At that time the first idea is: one thirty five seventy eighty wax, thirty one day never bad; Forty-six ninety-one, thirty days; February has 28 days in common years and 29 in leap years. A leap year is a year that is divisible by 4. Inner OS: Wow, this is a lot of judgment, so troublesome!!
However, the first method is implemented according to the above, and then I think about whether there is a relevant method to implement in Date, and I find it is OK by looking at the document. The second and third methods are implemented by Date. Specific ideas can refer to the following three implementation methods.
The first method
Implementation idea: Group the months 31 days and 30 days. If it is February, determine whether it is a leap year. If it is other months, determine whether it belongs to the 31-day month group or the 30-day month group.
function getLastDay(year, month) { const isLeapYear = ((year % 4)==0) && ((year % 100)! % = 0) | | (year 400) = = 0) const maxDays =,3,5,7,8,10,12 [1] const middleDays =,6,9,11 [4] the month = Number (month) if (the month == 2) { if (isLeapYear) { return 29 } else { return 28 } } else if (maxDays.includes(month)) { return 31 } else if (middleDays.includes(month)) { return 30 } }Copy the code
The second way
Implementation idea: Obtain the 00:00 time on the first day of the next month, subtract 1 second (milliseconds, minutes, hours), and output day to obtain the last day of the month.
function getLastDay(year, month) { return new Date(new Date(`${month<12? year:++year}-${month==12? 1:++month} 00:00`).getTime() - 1).getDate() }Copy the code
The third way
New Date(year,month, Date),month ranges from 0 to 11 (so that the month directly passed into the demand is the next month).
function getLastDay(year, month) {
const date1 = new Date(year, month, 0)
return date1.getDate()
}
Copy the code