JavaScript Date Object Setmonth method bug

Source: Internet
Author: User

In fact, there is no bug, but the JS date object to overflow time for their own processing.

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

The code is as follows Copy Code
var t = new Date ();
T.getmonth (); Output 0, now gets the correct value because the getmonth is indexed from 0
T.setmonth (3); Set Month to April
T.getmonth (); Output 4, where this should output 3 of the var t = new Date ();
T.getmonth (); Output 0, now gets the correct value because the getmonth is indexed from 0
T.setmonth (3); Set Month to April
T.getmonth (); Output 4,

Here should be output 3 you will find that you clearly set the month value of 3, but getmonth time output 4. At this point, you may be more puzzled. Let's take a look at the time now.

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

Specify the set date to April, but April is only 30 days, this time is 2013-04-31, but April is not 31 days. So JS processed the overflow date and automatically set the month to May 1

For this problem is also very good to solve, as long as the date before the Setmonth set to the monthly date, 1-28 can be.

  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.