how to use the formatisoduration function from the date-fns library in typescript

Here is an example of how to use formatIsoDuration function from date-fns library in TypeScript:

index.ts
import { formatISO, formatISO9075, formatDuration } from 'date-fns'

const duration = { minutes: 123, seconds: 45 }

const formattedDuration = formatDuration(duration, { format: ['hours', 'minutes'] })
console.log('Formatted Duration:', formattedDuration) // output: "2h 3m"

const startDate = new Date('2021-10-01T00:00:00.000Z')
const endDate = new Date('2021-10-01T02:03:45.000Z')

const durationInMs = Math.abs(endDate.valueOf() - startDate.valueOf())
const isoDuration = formatDuration(durationInMs, { format: ['hours', 'minutes', 'seconds'] })

console.log('ISO Duration:', isoDuration) // output: "2:03:45"

const iso8601 = formatISO(endDate)

console.log('ISO 8601:', iso8601) // output: "2021-10-01T02:03:45.000Z"

const iso9075 = formatISO9075(endDate)

console.log('ISO 9075:', iso9075) // output: "2021-10-01T02:03:45Z"
832 chars
23 lines

In the above example, we first import the required date-fns functions (formatISO, formatISO9075, formatDuration).

Next, we define the duration object with a value of 123 minutes and 45 seconds.

Then, we use the formatDuration function to format the duration object into a string that displays the duration in hours and minutes.

We also define a start and end date and calculate the duration between them in milliseconds. We use this duration value to pass to the formatDuration function, which formats the duration into an ISO 8601 duration string format.

Finally, we use the formatISO and formatISO9075 functions to format the end date into ISO 8601 and ISO 9075 date string formats, respectively.

gistlibby LogSnag