Javascript judges how many days of implementation code are there in a month of a year. Recommendation _ time and date

Source: Internet
Author: User
When I used to write a webpage, I often encountered the problem of selecting a date. In fact, I used to judge how many days a month has. The general practice is to first determine the number of months, and then determine the number of days (usually with a switch), if it is February, You have to determine whether the selected year is a leap year, then decide whether it is 28 days or 29 days. This is a very regular practice and logical.

However, if it is for the purpose, it is not so troublesome. The new Date ("xxxx/xx") Construction Method in JS has a wonderful place. When you input "xxxx/xx/0" (0) the date obtained is the last day of the previous month of the month (the maximum value of the Month of "xx" is 69. If "" is input ", "" is displayed ". The biggest benefit is that when you pass in "xxxx/3/0", you will get the last day of January 1, February, xxxx. It will automatically determine whether the year is a leap year and return 28 or 29. You do not have to judge it by yourself, it's so convenient !! Therefore, if we want to select the number of days in a month, we only need

The Code is as follows:


Var temp = new Date ("Select Year/select month + 1/0 ");
Alert (temp. getDate ());


That's all. Is it very convenient? This method can also be used for verification.
The getDaysInMonth (year, month) method written in JS is as follows:

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:

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
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.