JavaScript's getMonth() Returns Previous Month: A Datepicker Anomaly
Encountering discrepancies in date extraction from a datepicker can be puzzling. In particular, the getMonth() method may yield the previous month instead of the expected one. To illustrate this issue:
<code class="javascript">var d1 = new Date("Sun Jul 7 00:00:00 EDT 2013"); console.log(d1.getMonth()); // Output: 6 (June)</code>
Unveiling the Reason
The root cause lies in JavaScript's getMonth() method, which considers January as month 0 and December as month 11. As a result, if you obtain a Date object for a date in July, the getMonth() method will return 6, indicating June.
Rectifying the Anomaly
To resolve this issue and obtain the actual month number corresponding to the given date, simply increment the result of getMonth() by 1.
<code class="javascript">console.log(d1.getMonth() + 1); // Output: 7 (July)</code>
By adding 1 to the month number obtained from getMonth(), you can accurately capture the intended month.
The above is the detailed content of Why Does JavaScript\'s getMonth() Return the Previous Month for Dates in Some Months?. For more information, please follow other related articles on the PHP Chinese website!