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

[Question] How to get the difference between two dates as "N year, N months, N days"? #1100

Open
KidyasoVasiliy opened this issue Oct 1, 2020 · 3 comments

Comments

@KidyasoVasiliy
Copy link

Hello.
I have a function to get the period, but the problem is only days in a month.
Example

The documentation briefly describes diff, and as I understand it, you can't return the duration, only in a specific unit format
https://day.js.org/docs/en/display/difference

I want to get duration in the context of dates in which this period is specified.

Duration plugin, works without context, it doesn't fit
See issue

Who can help with this issue? Thx

@iamkun
Copy link
Owner

iamkun commented Oct 2, 2020

You can pass a unit as the second argument to get this diff in month or year

@stebogit
Copy link
Contributor

stebogit commented Oct 2, 2020

@KidyasoVasiliy try this:

const date1 = dayjs('2019-04-25')
const date2 = dayjs('2020-09-14')
const d = Math.abs(date1.diff(date2, 'day') % 365)
const m = Math.abs(date1.diff(date2, 'month') % 12)
const y = Math.abs(date1.diff(date2, 'year'))
console.log(`${y} year(s), ${m} month(s) and ${d} day(s)`) // 1 year(s), 4 month(s) and 143 day(s)

@KidyasoVasiliy
Copy link
Author

KidyasoVasiliy commented Oct 7, 2020

@KidyasoVasiliy try this:

const date1 = dayjs('2019-04-25')
const date2 = dayjs('2020-09-14')
const d = Math.abs(date1.diff(date2, 'day') % 365)
const m = Math.abs(date1.diff(date2, 'month') % 12)
const y = Math.abs(date1.diff(date2, 'year'))
console.log(`${y} year(s), ${m} month(s) and ${d} day(s)`) // 1 year(s), 4 month(s) and 143 day(s)

Thank you, this is almost what me need, but it still counts without period context. That is, high year is not taken into account - leap year

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