Convert time by jQuery

James picture James · Jun 28, 2011 · Viewed 9k times · Source

From the youtube player http://code.google.com/apis/ajax/playground/?exp=youtube#chromeless_player I get a time value in seconds, like '243.577'. Let it be a simple string.

How do I convert it to the value like: '04:35'? Like 4 minutes and 35 seconds (hope I made right calculations) for this example.

If the value is just 5 seconds, then it should give something like '00:05'. If negative, then '00:00'.

Answer

amosrivera picture amosrivera · Jun 28, 2011
var raw = "-54";

var time = parseInt(raw,10);
time = time < 0 ? 0 : time;

var minutes = Math.floor(time / 60);
var seconds = time % 60;

minutes = minutes < 10 ? "0"+minutes : minutes;
seconds = seconds < 10 ? "0"+seconds : seconds;

alert(minutes+":"+seconds);

Working demo: http://jsfiddle.net/8zPRF/

UPDATE

Some added lines for negative numbers and string format: http://jsfiddle.net/8zPRF/3/