Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time by jQuery

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'.

like image 864
James Avatar asked Dec 17 '22 12:12

James


2 Answers

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/

like image 189
amosrivera Avatar answered Dec 19 '22 08:12

amosrivera


You can do something like

var d = new Date(milliseconds);

You don't need jQuery for this.

like image 45
Mrchief Avatar answered Dec 19 '22 08:12

Mrchief