Home  >  Article  >  Web Front-end  >  How to determine how many days there are in a month using javascript

How to determine how many days there are in a month using javascript

青灯夜游
青灯夜游Original
2022-01-19 19:13:466621browse

Method: 1. Use the "new Date(year, month,0)" statement to create a date object based on the specified year and month; 2. Use the "date object.getDate()" statement to process the date object and return Specify the last day of the month to know how many days there are in the specified month.

How to determine how many days there are in a month using javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript method to determine how many days there are based on the month

If you want to get the number of days in a certain month, you only need to get the date of the last day of the month That’s it

Method 1:

Flexibly call setMonth(), getMonth(), setDate(), getDate() to calculate the required date

Implementation code:

function getMonthLength(date) {
  let d = new Date(date);
  // 将日期设置为下月一号
  d.setMonth(d.getMonth()+1);
  d.setDate('1');
  // 获取本月最后一天
  d.setDate(d.getDate()-1);
  return d.getDate();
}

Check it:

getMonthLength("2020-02-1")
getMonthLength("2021-02-1")
getMonthLength("2022-02-1")
getMonthLength("2022-03-1")

How to determine how many days there are in a month using javascript

Method 2:

It turns out there is a simpler way: call getDate() directly

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

Check it:

getMonthLength(2020,02)
getMonthLength(2021,02)
getMonthLength(2022,02)
getMonthLength(2022,03)
getMonthLength(2022,04)

How to determine how many days there are in a month using javascript

[Related recommendations: javascript learning Tutorial

The above is the detailed content of How to determine how many days there are in a month using javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn