mheavers
mheavers

Reputation: 30158

How to format HTML5 audio's currentTime property with Javascript

I am trying to format the HTML5 currentTime property using the following equation:

var s = parseInt(audio.currentTime % 60);

var m = parseInt((audio.currentTime / 60) % 60); duration.innerHTML = m + ':' + s ;

which works, only I want the seconds 1-9 to be displayed as :01 - :09 instead of :1 and :9 as they currently do. How would I write this code?

Upvotes: 6

Views: 10538

Answers (5)

Ivan Lencina
Ivan Lencina

Reputation: 1785

On TypeScript:

formatTime(seconds: number): string {

    let minutes: any = Math.floor(seconds / 60);
    let secs: any = Math.floor(seconds % 60);

    if (minutes < 10) {
        minutes = '0' + minutes;
    }

    if (secs < 10) {
        secs = '0' + secs;
    }

    return minutes +  ':' + secs;
}

Upvotes: -1

AJJJ
AJJJ

Reputation: 11

var currentTime = audio.currentTime | 0;

    var minutes = "0" + Math.floor(currentTime / 60);
    var seconds = "0" + (currentTime - minutes * 60);
    var cur = minutes.substr(-2) + ":" + seconds.substr(-2);

Upvotes: 0

standup75
standup75

Reputation: 4814

That may help you, I used that:

  function formatTime(seconds) {
    minutes = Math.floor(seconds / 60);
    minutes = (minutes >= 10) ? minutes : "0" + minutes;
    seconds = Math.floor(seconds % 60);
    seconds = (seconds >= 10) ? seconds : "0" + seconds;
    return minutes + ":" + seconds;
  }

Upvotes: 28

Thai
Thai

Reputation: 11354

You just have to add a single 0 if s is less than 10. After

var m = parseInt((audio.currentTime / 60) % 60);

put

if (s < 10) {
    s = '0' + s;
}

The code is pretty straightforward.

Upvotes: 0

Aston
Aston

Reputation: 3712

if (m < 10) m = '0' + m; 
if (s < 10) s = '0' + s;

Upvotes: 2

Related Questions