开发者

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 th开发者_运维知识库is example.

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


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/


You can do something like

var d = new Date(milliseconds);

You don't need jQuery for this.


I find the Date.js library extremely helpful when dealing with dates. It extends the built in javascript Date object.

E.g.

var timeString = new Date(seconds * 1000).toString('mm:ss');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜