getMonth() in JavaScript: Why it Returns the Previous Month
When working with the getMonth() method in JavaScript, it's important to understand its behavior. In your case, you are receiving the previous month because getMonth() starts its count from 0. This means that January is considered month 0, February is month 1, and so on.
Example
In the code provided, d1 represents the date "Sun Jul 7 00:00:00 EDT 2013." When you call d1.getMonth(), it returns 6 because July is the seventh month (remember, counting starts from 0).
Solution
To obtain the correct month value, you need to add 1 to the result returned by getMonth(). This will shift the index by 1, giving you the actual month number.
<code class="javascript">var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013"); d1.getMonth() + 1; //returns 7 (correct month)</code>
By understanding the behavior of getMonth(), you can avoid confusion and accurately retrieve the correct month value.
The above is the detailed content of Why Does getMonth() in JavaScript Return the Previous Month?. For more information, please follow other related articles on the PHP Chinese website!