Google Apps Script get current month from Date()

Google Apps Script get current month from Date()



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.


getMonth()


Date




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.


Date



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.


date2






JavaScript counts months from 0 to 11. January is 0. December is 11.

– Airwavezx
Jul 16 '18 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 object date2, which should be (according to the official docs) "2014-02-01"

– Philipp Zettl
Jul 16 '18 at 13:58


Date


date2


"2014-02-01"






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
Jul 16 '18 at 14:01


console.log(date2)


Sat Feb 01 2014 00:00:00 GMT+0200 (Israel Standard Time)






Thanks for pointing that out, looks like I forgot about the TZ.. thanks!

– Philipp Zettl
Jul 16 '18 at 14:11




1 Answer
1



As @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);



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)