2

I run this in node.js v11.6.0

const now = new Date(Date.now());
let date = now;
date.setFullYear(date.getFullYear() - 1);
let str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
while(!data[str]){
    date = date.setDate(date.getDate() - 1);
    str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
}

And get:

trail.js:15 str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
TypeError: date.getFullYear is not a function

inside the while loop date.setDate() works but date.getFullYear() is not a function all of a sudden.

Cmac c
  • 55
  • 6
  • Always worth [checking the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate)... – T.J. Crowder Dec 24 '19 at 17:36
  • `new Date(Date.now())` will produce an identical result to `new Date()`. – RobG Dec 25 '19 at 07:20

1 Answers1

3

When you call date.setDate(date.getDate() - 1); you're assigning the return value of setDate which is an integer to date. That's why you can't call .getFullYear later, since numbers don't have that method.

From MDN:

Return Value

The number of milliseconds between 1 January 1970 00:00:00 UTC and the given date (the Date object is also changed in place).

while(!data[str]){
    date.setDate(date.getDate() - 1);
    str = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
}

Have in mind that date.getMonth() returns an integer number, between 0 and 11. If you want to format it correctly you can check:

Format JavaScript date as yyyy-mm-dd

Marcos Casagrande
  • 29,440
  • 5
  • 62
  • 77