4

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

James
  • 42,081
  • 53
  • 136
  • 161

3 Answers3

11
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/

Miro
  • 186
  • 4
  • 8
amosrivera
  • 26,114
  • 9
  • 67
  • 76
  • for -54 it gives -1:-54, it would be perfect, if you fix that – James Jun 28 '11 at 01:06
  • 1
    This is great, but you should be doing either "minutes <= 9" or "minutes < 10". As it is, 0-8 have a zero added to them, 9 drops to a single digit. Thanks for the code! – Jake May 27 '13 at 20:13
1

You can do something like

var d = new Date(milliseconds);

You don't need jQuery for this.

Mrchief
  • 75,126
  • 20
  • 142
  • 189
0

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');
jacob.toye
  • 1,212
  • 11
  • 14