最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google Apps Script get current month from Date() - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question asked Jul 16, 2018 at 13:44 Philipp ZettlPhilipp Zettl 1961 gold badge3 silver badges18 bronze badges 4
  • 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 object date2, 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
Add a ment  | 

1 Answer 1

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论