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

3 Answers 3

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/

2
  • for -54 it gives -1:-54, it would be perfect, if you fix that
    – James
    Jun 28, 2011 at 1: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, 2013 at 20:13
1

You can do something like

var d = new Date(milliseconds);

You don't need jQuery for this.

2
  • once you have a date object, you can format it any way you want.
    – Mrchief
    Jun 28, 2011 at 1:01
  • 3
    if I know how to do that, I would not ask
    – James
    Jun 28, 2011 at 1:03
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');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.