Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

date1.diff(date2, 'day') does not produce expected result #684

Open
bschwartz757 opened this issue Sep 30, 2019 · 2 comments
Open

date1.diff(date2, 'day') does not produce expected result #684

bschwartz757 opened this issue Sep 30, 2019 · 2 comments

Comments

@bschwartz757
Copy link

Describe the bug
I'm using .diff() with two dayjs objects to calculate a duration. However, this doesn't seem to work with day. Example:

const duration = (start, end) => {
  const daysDiff = end.diff(start, 'day'); // produces `0`, expected `1`
  const hoursDiff = end.diff(start, "hour"); // expected result
  const minutesDiff = end.diff(start, "minute") % 60; // expected result
  return `${daysDiff} day ${hoursDiff} hr ${minutesDiff} mins`;
}

duration("2019-09-28T23:00:00", "2019-09-29T00:00:00")
// -> 1 day 1 hr

However, if I use const daysDiff = end.date() - start.date(); then I get the expected result.
Expected behavior
See above (expect daysDiff to be 1)
-> 1 day 1 hr

Information

  • Day.js Version 1.8.16
  • OS: Mac OS Mojave Version 10.14.2
  • Browser: Chrome Version 77.0.3865.90
  • Time zone: GMT-07:00 DST (Pacific Daylight Time)
@iamkun
Copy link
Owner

iamkun commented Oct 1, 2019

const start =  dayjs("2019-09-29T00:00:00")
const end = dayjs("2019-09-28T23:00:00")

end.diff(start, 'day', true); //  -0.0416

If you add true as the third argument, you will get the diff result in float.
In this way, it's easy to find out that the actuall diff in only '0.04' day (1 hour) , so the result 0 is expected. (Math.round(0.04) // 0)

@kthatoto
Copy link

@bschwartz757
I had same problem, but I found the solution for yours.

const duration = (start, end) => {
-  const daysDiff = end.diff(start, 'day');
+  const daysDiff = end.startOf('day').diff(start.startOf('day'), 'day'); // produces `1`
  ...
}

I think currently behavior of diff is spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants