1

i have a string of like 120 i want to convert into time like 02:00(hh:mm). Actual :

120

Expected:

02:00.

so, please suggest result.

4
  • Just time - then the best is to use moment.js Commented Nov 21, 2014 at 12:54
  • yes only want time in javascript Commented Nov 21, 2014 at 12:56
  • How come 120 is 2:00? Commented Nov 21, 2014 at 12:56
  • @SalmanA - you think it might be seconds? Commented Nov 21, 2014 at 12:57

3 Answers 3

3

Fiddle: http://jsfiddle.net/ow418gLc/1/

var value = 120
var hours = pad(Math.floor(value / 60));
var minutes = pad(value % 60);

function pad(n){
    n = n.toString();
    n = n.length < 0 ? n: ("0" + n);
    return n;
};

console.log(hours + ":" + minutes);

output:

02:00

EDIT: There is a small bug in the padding above and I converted this to a real function.

function convertMinutesToTime(minutes) {
    function pad(n) {
        n = n.toString();
        n = n.length < 2 ? ("0" + n) : n;
        return n;
    };
    var paddedHours = pad(Math.floor(minutes / 60));
    var paddedMinutes = pad(minutes % 60);

    return paddedHours + ":" + paddedMinutes
}

console.log(convertMinutesToTime(120));
Sign up to request clarification or add additional context in comments.

2 Comments

it gives 00:020 expected- 02:00.
Does the edit version work for you? Here is the fiddle: jsfiddle.net/ow418gLc/2
1
var mins = 120;

var h = Math.floor(mins / 60);
var t = (h < 10 ? "0" + h : h) + ":" + ("00" + mins % 60).slice(-2);

Comments

1

You'd probably need to do three steps:

  1. Turn a string into a number:

    var number = parseInt(string, 10);
    
  2. Create a Date from a number of seconds:

    var date = new Date(2000, 0, 1, 0, 0, seconds);
    
  3. Create a formatted date string from a Date. For that, you might like to use moment.js and do:

    var formatted = moment(date).format('hh:ss');
    

Comments

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.