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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Problem with intervalToDuration function - undefined is not included in output as 0 #3658

Open
SimonVillage opened this issue Jan 9, 2024 · 6 comments 路 May be fixed by #3758
Open

Problem with intervalToDuration function - undefined is not included in output as 0 #3658

SimonVillage opened this issue Jan 9, 2024 · 6 comments 路 May be fixed by #3758

Comments

@SimonVillage
Copy link

There is an issue with the intervalToDuration function

The problem

馃捇 Code demonstrating the problem

import { intervalToDuration } from 'date-fns'

const output = intervalToDuration({
start: new Date(1929, 0, 15, 12, 0, 0),
end: new Date(1968, 3, 4, 19, 5, 0)
})

console.log(output)
//=> {years: 39, months: 2, days: 20, hours: 7, minutes: 5}

馃檨 Actual behavior

seconds is not included. The documentation however shows an object output with seconds: 0

馃檪 Expected behavior

seconds should be included in the output with value 0

Debug information

  • date-fns version: 3.1.0
@kossnocorp
Copy link
Member

Hey! Thank you for the report. The docs are indeed outdated. For compactness's sake, 0 values are omitted starting from v3. Is there a specific use case for that?

@SimonVillage
Copy link
Author

SimonVillage commented Jan 9, 2024

We would like to format it to a "time left" string like 1h 0m 32s. As in the docs we expected minutes to be 0 rather than undefined / not existent.

So to fix this we do something like this right now:

return `${hours || 0}h ${minutes || 0}m ${seconds || 0}s`

@kossnocorp
Copy link
Member

@SimonVillage I see, thank you! Yeah, I guess you'll have to go with that. The types also reflect it if that is of any help. I'll make sure to update the docs. Thanks!

@SimonVillage
Copy link
Author

I wonder if we can't add an options parameter with zero: true?

@kossnocorp
Copy link
Member

@SimonVillage I don't think it's a bad idea, a PR is welcome. If you decide to make it happen, please also add the NormalizedDuration version of the return type and conditionally return it from the function. Tell me if you need help with generics

export type NormalizedDuration = Required<Duration>

@princemaple
Copy link

0 values are omitted starting from v3

This seems like a very bad move. Function return values should have a definitive shape. Just got bit by it.

grgr-dkrk added a commit to grgr-dkrk/date-fns that referenced this issue Apr 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Planning
Development

Successfully merging a pull request may close this issue.

3 participants