Search code examples
javascriptdayjs

Convert milliseconds to more than 24 hours using Dayjs Library


How to convert milliseconds to more than 24 hours format? I am using Dayjs library but I could not figure out how to make the time format more than 24 hours.

In the code snippet below, the display should be 45:00:00.

For some reasons the output is not properly displaying on the code snippet so I also added it on jsfiddle.

dayjs.extend(dayjs_plugin_duration)

const dates = [
    {
        start: 1674748800000,
        end: 1674831600000
    },
    {
        start: 1674748800000,
        end: 1674828000000
    }
]
const totalEachDate = []
dates.filter( date => {
    const dayjsStart = dayjs( date.start )
    const dayjsEnd = dayjs( date.end )
    const total = dayjs.duration( dayjsEnd.diff( dayjsStart ) ).$ms
    totalEachDate.push( total ) // output: 23:00:00 and 22:00:00
} )

const addDates = totalEachDate.reduce( ( total, num ) => dayjs( total ) + dayjs( num ), 0 )

console.log( dayjs.duration( addDates ))
// this will display an object
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/plugin/duration.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>


Solution

  • To convert milliseconds to hours greater than 24 hours, you can use the Dayjs library and perform a simple calculation to convert the milliseconds to hours, minutes, and seconds.You can then display the results as a string using a template expression.

    Here is the code that performs the conversion :

    const totalMilliseconds = addDates
    const totalSeconds = Math.floor(totalMilliseconds / 1000)
    const totalMinutes = Math.floor(totalSeconds / 60)
    const totalHours = Math.floor(totalMinutes / 60)
    
    console.log(`${totalHours}:${totalMinutes % 60}:${totalSeconds % 60}`)
    

    Adds zeros for the display of hours, minutes, and seconds.

    console.log(`${("0" + totalHours).slice(-2)}:${("0" + (totalMinutes % 60)).slice(-2)}:${("0" + (totalSeconds % 60)).slice(-2)}`)