admin管理员组

文章数量:1391999

I'm using date-fns to calcualte day differences

import differenceInDays from "date-fns/differenceInDays";

console.log(
  differenceInDays(
    new Date("2020-08-12T07:22:03.498Z"),
    new Date("2020-08-09T09:30:20.914Z")
  )
);

The answer is 2, I'm expecting 3, since 12-9 is 3.

What's wrong? =/src/index.js:0-299

I'm using date-fns to calcualte day differences

import differenceInDays from "date-fns/differenceInDays";

console.log(
  differenceInDays(
    new Date("2020-08-12T07:22:03.498Z"),
    new Date("2020-08-09T09:30:20.914Z")
  )
);

The answer is 2, I'm expecting 3, since 12-9 is 3.

What's wrong? https://codesandbox.io/s/date-fns-v2-pzlex?file=/src/index.js:0-299

Share Improve this question asked Aug 9, 2020 at 11:09 akiboakibo 7151 gold badge13 silver badges27 bronze badges 2
  • 2 It's not whole 3 days. It's 2 days and 21 hours. Therefore date-fns returns 2 – Harun Yilmaz Commented Aug 9, 2020 at 11:12
  • 1 @HarunYilmaz how to ignore the time? I just want the day difference – akibo Commented Aug 9, 2020 at 11:12
Add a ment  | 

3 Answers 3

Reset to default 7

Difference in whole days

The reason for getting full days only is that that is how that API works as per the official docs for DifferenceInDays

Difference in calendar days

What you're looking for is the difference in calendar days, which is natively supported by date-fns as can be seen in the documentation for differenceInCalendarDays.

Underwater this API just strips the time, which seems to be what you are looking for.

Example

import differenceInCalendarDays from "date-fns/differenceInCalendarDays";

console.log(
  differenceInCalendarDays(
    new Date("2020-08-12T07:22:03.498Z"),
    new Date("2020-08-09T09:30:20.914Z")
  )
);

If you want to get only the date, remove the time until the timezone

console.log(
  differenceInDays(
    new Date("2020-08-12"),
    new Date("2020-08-09")
  )
);

// returns 3

It should show the number of full days between the given dates. (You lack a few hours for 3 plete days)

So, if you change the final date time to new Date("2020-08-12T09:30:20.914Z")

It will show 3 days.

本文标签: nodejsdifferences in days lack of 1 days (javascript)Stack Overflow