how to use the formatduration function from date-fns in javascript

To use the formatDuration function from date-fns, you need to first import it from the library:

index.tsx
import { formatDuration } from 'date-fns'
42 chars
2 lines

Then, you can provide the function with a duration in milliseconds and an object specifying the format to use. For example, if you want to format a duration of 1 hour, 23 minutes, and 45 seconds to display as "1:23:45":

index.tsx
const durationInMs = 5025000 // 1 hour, 23 minutes, 45 seconds
const format = { hours: true, minutes: true, seconds: true }
const formattedDuration = formatDuration(durationInMs, format)
console.log(formattedDuration) // "1:23:45"
231 chars
5 lines

In the format object, you can specify which units of time you want to include in the output (hours, minutes, seconds), as well as any separators you want to use between them. For example, if you want to use colons as separators, you can add the following property to the format object:

index.tsx
const format = { hours: true, minutes: true, seconds: true, delimiter: ':' }
77 chars
2 lines

This would produce output in the format "1:23:45".

gistlibby LogSnag