Skip to content

formatMediaTime() Helper Method

The formatMediaTime() Helper Method module provides a helper function that returns a string formatted as minutes:seconds time code for time-based media.

Import

To import the formatMediaTime() Helper Method:

javascript
import { formatMediaTime } from '@obewds/vueventus'

Arguments

Returns: String

ArgsTypeStatusDescription
currentTimeString or NumberRequiredA number or string representing time in seconds

Use Examples

javascript
console.log( formatMediaTime(2.123) )
// returns (string): '00:02'

console.log( formatMediaTime(122.123) )
// returns (string): '02:02'

console.log( formatMediaTime('122.123') )
// returns (string): '02:02'

console.log( formatMediaTime(6069) )
// returns (string): '01:41:09'

console.log( formatMediaTime(6069) )
// returns (string): '01:41:09'

console.log( formatMediaTime(806069) )
// returns (string): '09:07:54:29'

Module Code

ts
// ./src/helpers/formatMediaTime.ts

export default function (currentTime: string|number): string {

    let sec_num = parseInt(String(currentTime), 10)

    let days = Math.floor(
        parseInt(
            String( Number(sec_num) / (24 * 3600) )
        )
    )
 
    sec_num = sec_num % (24 * 3600)
    let hours = Math.floor(
        parseInt(
            String( Number(sec_num) / 3600 )
        )
    )

    sec_num %= 3600
    let minutes = Math.floor(sec_num / 60)

    sec_num %= 60
    let seconds = Math.floor(sec_num)

    let sDays = days < 10 ? "0" + days : days
    let sHrs = hours < 10 ? "0" + hours : hours
    let sMins = minutes < 10 ? "0" + minutes : minutes
    let sSecs = seconds < 10 ? "0" + seconds : seconds

    let output = sDays === '00' ? '' : sDays + ':'
    output += sHrs === '00' ? '' : sHrs + ':'
    output += sMins + ':' + sSecs
    
    return output

}

Released under the MIT License