I'm currently working on a function to generate data according to a start and an end date.
While I was testing my functions I've realized some wrong calculated values.
Long story short the getMonth()
method for Date
objects is returning a unexpected value.
var date = new Date();
console.log(date.getMonth());
var date2 = new Date(2014, 1, 1);
console.log(date2);
I'm currently working on a function to generate data according to a start and an end date.
While I was testing my functions I've realized some wrong calculated values.
Long story short the getMonth()
method for Date
objects is returning a unexpected value.
var date = new Date();
console.log(date.getMonth());
var date2 = new Date(2014, 1, 1);
console.log(date2);
Can someone explain to me the reason why to start a month at 0, even if it's not possible to create a right Date
object using that index.
Even though date2
my second example is from the official docu of JS and is returning a unexpected value according to the example giving in the "Parameters" section.
- 2 JavaScript counts months from 0 to 11. January is 0. December is 11. – Airwavezx Commented Jul 16, 2018 at 13:49
-
Yes, I totally understand that and it could be a better way to calculate with those
Date
objects, but it doesn't answer the question about my created objectdate2
, which should be (according to the official docs)"2014-02-01"
– Philipp Zettl Commented Jul 16, 2018 at 13:58 -
When I run
console.log(date2)
in my Chrome I get:Sat Feb 01 2014 00:00:00 GMT+0200 (Israel Standard Time)
So it behaves the way you expect it to. – Airwavezx Commented Jul 16, 2018 at 14:01 - Thanks for pointing that out, looks like I forgot about the TZ.. thanks! – Philipp Zettl Commented Jul 16, 2018 at 14:11
1 Answer
Reset to default 3As @Airwavezx mentioned the code was correct.
tl;tr I forgot to use timezones and JS is counting months from 0
So a solution to my question could be:
var date = new Date();
console.log(date.getMonth()+1);
var date2 = new Date("2014-01-01T00:00:00Z");
console.log(date2);