JS gets the instance code for the last day of the month with JS getting the maximum number of days of the month

  • 2020-03-30 00:55:58
  • OfStack

<html xmlns="http://www.w3.org/1999/xhtml" >   
<head>   
<title> Title page </title>   
<script language="javascript">   
function getLastDay(year,month)   
{   
 var new_year = year;  //Take the current year
 var new_month = month++;//Take off the first day of the next month for easy calculation (the last day is not fixed)
 if(month>12)      //If the current is greater than December, the year moves to the next year
 {   
 new_month -=12;    //Reduction in
 new_year++;      //Year to add
 }   
 var newnew_date = new Date(new_year,new_month,1);        //Take the first day of the current month
 return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//Gets the date of the last day of the month
}   
</script>   
<body>   
  <input id="Button1" type="button" value=" take 2007 years 5 Last day of the month " onClick="alert(getLastDay(2007,5))" />   
</body>   
</html>  

Js gets the maximum number of days in a month

The new Date(" XXXX /xx/xx") in JS has a nice construction method,

When you pass in "XXXX /xx/0" (no. 0), you get the date of the last day of the previous month of "xx" (the maximum value of "xx" month is 69, digression),

When you pass "XXXX /xx/1" (date 1), you will get the date of the first day of the following month of "xx".

If you pass "1999/13/0", you get "1998/12/31". And the great thing is that when you pass in "XXXX /3/0", you get the last day of February, XXXX, and it automatically returns 28 or 29 for the leap year.

So, if we want to figure out how many days there are in the year, in the month, we just need to

Var temp=new Date(" select year/select month +1/0");

Return temp.getdate ()// maximum number of days

And if you want to verify it, you can also do it this way.

The following is the getDaysInMonth(year, month) method written in JS to get the number of days in a certain year and month:


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

The method to get the days of a month with javascript is as follows:

Goal: to obtain the number of days in 2014/april


//Construct a date object:
var day = new Date(2014,4,0); 
//Acquisition days:
var daycount = day.getDate();

Description: OK, the number of days you want has come out. Note: when we construct the date object, 4 is actually the actual month of may, because the month starts at 0. And then the third number of days is 0, and the minimum number is 1, which is less than 1, which is the last day of march that you want.


Related articles: