Reez0
Reez0

Reputation: 2689

getMonth() returning the following day for some reason

I'm retrieving a list of dates from my database and getting the month from those dates. When I get month for this date it returns 0 for January.

var date = new Date('2015-12-31T22:57:12.000Z').getMonth();

When I get month for a similar date it returns 11 for December.

var date2 = new Date('2015-12-31T12:24:29.000Z').getMonth();

Upvotes: 0

Views: 210

Answers (3)

vipul patel
vipul patel

Reputation: 736

As you want to why this both Dec string dates returning different month? This is the answer:

From your profile i could see your are from south Africa which is GMT+2 timezone.

First date string : 2015-12-31T22:57:12.000Z, which is 31 Dec and 22.57 hours mid night. While creating date object out of string date at client browser side, It's takes your local timezone into account. Its GMT + 2.

Thus, it adds 2 hours: 2015-12-31T22:57:12.000Z + 2 hours => 22.57 hours shift to next day after addition of 2 hours(22.57 +2 => next day 00.57), which would be January month morning 0.57 hours. So it returns 0 (January) Month.

While second : 2015-12-31T12:24:29.000Z which is 12:24 hours which shifts to 14.24 in same day after addition on 2 hours as above. So you are still in 31 Dec. hence you receive December for this.

Upvotes: 1

dmitri7
dmitri7

Reputation: 193

This will give the right result:

var date = new Date('2015-12-31T22:57:12.000Z').getUTCMonth();

If your timezone is GMT+02, then you can try like this also:

var date = new Date('2015-12-31T22:57:12.000+0200').getMonth();

Upvotes: 4

Akshay Bande
Akshay Bande

Reputation: 2587

The months in javascript are numbered from 0 to 11, days from 1 to 31

Upvotes: -1

Related Questions