Skip to content Skip to sidebar Skip to footer

Javascript Date Returns Wrong Month If Day Is 01

I am trying to get correct month from the date string, this works fine as long as the day isn't the first of the month (01). If the day is the first, it returns the previous month:

Solution 1:

The actual problem lies within the timezone of your computer.

Suppose that your computer is in Eastern Time (GMT-5):

var foo = newDate('2014-12-01');

foo.toUTCString(); // "Mon, 01 Dec 2014 00:00:00 GMT"
foo.toISOString(); // "2014-12-01T00:00:00.000Z"
foo.toString(); // "Sun Nov 30 2014 19:00:00 GMT-0500 (Eastern Standard Time)"

Notice that the date is actually in November because it's a few hours behind, and therefore the zero-indexed month would be 10. JavaScript automatically assumes UTC when you do not provide a time string.

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year.

In local time, this Date object represents November 30 at 19h00 (7pm), so getMonth() returns 10:

foo.getMonth(); // 10
foo.getUTCMonth(); // 11

If you are not concerned about time zones and are just dealing with dates, perhaps look into using the getUTC* methods.

You can read more about the Date object here. Hope this helps.

Solution 2:

JavaScript is doing what it should do. In the day value it interprets the 01 as 0, and a zero value for the day is interpreted as the last day of the previous month. It's like asking for day 32 in a month with 31 days. That would return a date of the first of the next month.

Solution 3:

getMonth() returns a value from 0 to 11: http://www.w3schools.com/jsref/jsref_getmonth.asp January is 0, February is 1, and so on.

So to get the 'right' month, you should do +1.

Post a Comment for "Javascript Date Returns Wrong Month If Day Is 01"