Skip to content
Advertisement

JavaScript: How to convert a Number into Time Format

can someone help me?

function convertTime() {
    var num = 730;
    var result = num.ConvertToTimeOrSomethingIDK;

    console.log(result); // Result should be 7:30
}

Thank you!

Advertisement

Answer

This should work:

function convertTime(num) {
    var numberString = num.toString();

    // Add "0"s to start so that it is at least 3 digids long. Necessary for times between 0:00 and 0:59
    while (numberString.length < 3)
        numberString = "0" + numberString;

    var minutes = numberString.slice(-2);
    var hours = numberString.slice(0, -2);

    return hours + ":" + minutes;
}

Try out here:

console.log(720, convertTime(720));
console.log(1010, convertTime(1010));
console.log(500, convertTime(500));
console.log(0, convertTime(0));



function convertTime(num) {
    var numberString = num.toString();
    
    while (numberString.length < 3) 
      numberString = "0" + numberString;
    
    var minutes = numberString.slice(-2);
    var hours = numberString.slice(0, -2);

    return hours + ":" + minutes;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement