Home > Web Front-end > JS Tutorial > body text

Javascript implementation code to determine how many days there are in a certain month in a certain year Recommended_time and date

WBOY
Release: 2016-05-16 18:44:55
Original
955 people have browsed it

The general approach is to first determine which month it is, and then decide how many days it has (usually using switch). If it is February, you have to determine whether the selected year is a leap year, and then decide whether it has 28 or 29 days. This is a very regular approach and also very logical.

However, if it is to achieve the purpose, there is no need to go to such trouble. The new Date("xxxx/xx/xx") date construction method in JS has a wonderful thing. When you pass in "xxxx/xx/0" (number 0), the date obtained is "xx" The last day of the month before the month (the maximum value of the "xx" month is 69, off topic), if you pass in "1999/13/0", you will get "1998/12/31". And the biggest advantage is that when you pass in "xxxx/3/0", you will get the last day of February of xxxx year. It will automatically determine whether it is a leap year and return 28 or 29. You don't have to judge by yourself. It's so convenient! ! Therefore, if we want to select how many days there are in the selected year and month, we only need to

Copy the code The code is as follows:

var temp=new Date("Select year/select month 1/0");
alert(temp.getDate());

That’s it, isn’t it very convenient? ? For verification, you can also use this method.
The following is the getDaysInMonth(year, month) method written in JS to get the number of days in a certain year and month:
Copy code The code is as follows:

function getDaysInMonth(year,month){
month = parseInt(month,10) 1;
var temp = new Date(year "/" month " /0");
return temp.getDate();
}

The following is a simple test code:

[Ctrl A select all Note: If you need to introduce external Js, you need to refresh to execute
]<script> function getDaysInMonth(year,month){ month = parseInt(month,10)+1; var temp = new Date(year+"/"+month+"/0"); return temp.getDate(); } alert(getDaysInMonth("2009","11")); </script>
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template