1
console.log(dateFns.formatDistanceToNowStrict(new Date(2021,08,23),
{ unit:'day'})) // returns 87 days when it should be 58 days

console.log(dateFns.format(new Date(), 'dd.MM.yyyy')) //displays the correct current date

I don't know why it is displaying 87 days on my discord.js bot instead of 59 days(That's like a whole month away, don't think it's a timezone issue).

Any idea what could be wrong with it, I'm trying to get time between now and another date and I'm using Date Fns, The roundings don't work either

Scent
  • 27
  • 3

2 Answers2

2

Your problem is fairly simple. The month in the new Date() constructor is 0-indexed. That means if you want to set 08 (August) as your month you actually have to pass 07 since January is 00 and not 01.

// With 08 as month ❌
const difference1 = new Date(2021, 08, 23) - new Date();
console.log(`08: ${difference1 / 1000 / 60 / 60 / 24} days`);

// With 07 as month ✔️
const difference2 = new Date(2021, 07, 23) - new Date();
console.log(`07: ${difference2 / 1000 / 60 / 60 / 24} days`);
Behemoth
  • 5,389
  • 4
  • 16
  • 40
  • The leading zeros for numbers are misleading. In old implementations (and some other programming languages) they are interpreted as Octal, e.g. [*How do I work around JavaScript's parseInt octal behavior?*](https://stackoverflow.com/questions/850341/how-do-i-work-around-javascripts-parseint-octal-behavior). – RobG Jun 28 '21 at 00:50
0

Okay figure it out.

console.log(dateFns.formatDistanceToNowStrict(new Date(2021,08,23),
{ unit:'day'}))

Change the date format to

console.log(dateFns.formatDistanceToNowStrict(new Date('2021-08-23'),
{ unit:'day'}))
Scent
  • 27
  • 3
  • `new Date(2021,08,23)` creates a local date for 23 Sep 2021, whereas `new Date('2021-08-23')` creates a UTC date for 23 Aug 2021. – RobG Jun 28 '21 at 00:48