2

I have a timecode that is in seconds, to three places past the decimal. (e.g. 10.675) I'd like to format it to read mm:ss (e.g. 00:32 or 23:04). Is there a Javascript or jQuery base function that does that? Whenever I search I only find how to add times to datepickers.

2 Answers 2

2

Try something like the below:

function formateDate( seconds ) {
    var date = new Date(seconds * 1000);
    return date.getMinutes() + ":" + date.getSeconds();
}

This will create a new date where you can focus on the time aspect. This will not work well if you need to go over 24 hours though. For that you'd need two dates that you compare. Or just do the calculations manually using divide and modulus.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/

Sign up to request clarification or add additional context in comments.

Comments

1

I don't believe jQuery has any support by default for this, but it's fairly simple to write your own. For example:

function formatTime(seconds) {
    var mins = Math.floor(seconds/60),
        secs = Math.floor(seconds) - (60*mins);
    return (mins < 10 ? '0' + mins : mins) + ':' + (secs < 10 ? '0' + secs : secs);
}

However, this does not work well if the timecode is larger than 60 minutes, in which case you'd just need to add hours.

2 Comments

Cool, this works, but how do I add the trailing zeros (i.e. force the mins and secs to each have at least two digits?)
nm, I used this: function pad(number, length) { var str = '' + number; while (str.length < length) { str = '0' + str; } return str;

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.