Javascript Date object setMonth method bug

Source: Internet
Author: User

This article will detail the bugs and Solutions of the setMonth method of the javascript Date object. For more information, see.

In fact, I can't talk about any bugs, but the JS Date object handles the overflow time.

First, set your system time to January 31, 2013. This step is very important, otherwise this BUG may not occur, and then execute the following code

 

The Code is as follows: Copy code
Var t = new Date ();
T. getMonth (); // output 0. The correct value is obtained because getMonth is indexed from 0.
T. setMonth (3); // you can specify the month as January 1, April.
T. getMonth (); // output 4. The var t = new Date () of 3 should be output here ();
T. getMonth (); // output 0. The correct value is obtained because getMonth is indexed from 0.
T. setMonth (3); // you can specify the month as January 1, April.
T. getMonth (); // output 4,

Here you should output 3, and you will find that you set the Month value to 3, but output 4 in getMonth. At this time, you may be confused. Let's take a look at the current time.

 

The Code is as follows: Copy code
Console. log (t); // Wed May 01 2013 11:47:31 GMT + 0800 (CST) console. log (t); // Wed May 01 2013 11:47:31 GMT + 0800 (CST) setMonth (3)

Specify the date to July 31, but only 30 days in July 31, but not 31 days in July 31. Therefore, js processes the overflow date and automatically sets the month to May 1.

This problem can also be well solved, as long as you set the date to the date that is available every month before setMonth, 1-28 can be done.

The Code is as follows: Copy code


Var t = new Date ();
T. setDate (1 );
T. setMonth (3 );
T. getMonth (); // output 3

Related Article

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.