0

There seems to be an error with the Date object in Javascript, it thinks April 31, 2017 is a real day. I discovered this by trying to get the date 90 days ago from today (August 29). The following is a snippet of my code for context:

*Edit: For context, this is in Google Apps Script technically.

var now = new Date();
var ninetyDaysAgo = new Date(now.getTime() - 90 * 1000 * 60 * 60 * 24);
var dateStr = ninetyDaysAgo.getFullYear() + '-' + 
              ninetyDaysAgo.getMonth() + '-' + 
              ninetyDaysAgo.getDate();
//If I print dateStr it's '2017-4-31'

This is important because I need the correct date to use an API. Is this just a thing in the date class or am I missing something?

Alisa
  • 21
  • 2
  • 1
    5/31 is May 31st? I think you might be getting your months mixed up. – AJ X. Aug 29 '17 at 19:04
  • 1
    @axlj Yes it is. – JstnPwll Aug 29 '17 at 19:05
  • hmm.. I double checked my logs and I'm getting 4-31-17.... Let me update the post with more code – Alisa Aug 29 '17 at 19:08
  • "4-31-17" is not something the `toString` function of a date object would return. Are you using [`getMonth`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth)? Are you aware that it is zero-based? – str Aug 29 '17 at 19:10
  • I just updated my code and I realized my mistake is that I forgot the months are zero based......Time for a break. Thank you very much str. – Alisa Aug 29 '17 at 19:11

1 Answers1

1

getMonth is zero-based. So you need to use it like below:

var dateStr = ninetyDaysAgo.getFullYear() + '-' + 
              (ninetyDaysAgo.getMonth() + 1) + '-' + 
              ninetyDaysAgo.getDate();
str
  • 42,689
  • 17
  • 109
  • 127