Search code examples
javascriptjqueryjquery-calculation

Javascript Convert Hours and Minutes into Days


I'm sorry if something similar might be discussed before, but I really need help with it.

Bellow is the code all I want to do is if the number goes over 24h it should switch to 1 day and 0 h, I can't figure it out if someone can please explain how to do it that would be so kind. I'm using it to calculate minutes and hours and want to have also days calculations if the number is higher then 24h.

Thanks in advance

    //minutes to hour converter
    function ConvertMinutes(num){
      h = Math.floor(num/60);
      m = num%60;
      return(h + "hours"+" :"+" "+m+"minutes").toString();
    }

    var input = 68.68

    console.log(ConvertMinutes(input));

Solution

  • You just need to divide the num by 1440, which is 24 hours in minutes... Then you need a condition to display the "x days," when there is a value.

    I also suggest you to round the minutes...
    ;)

    //minutes to hour (and days) converter
    function ConvertMinutes(num){
      d = Math.floor(num/1440); // 60*24
      h = Math.floor((num-(d*1440))/60);
      m = Math.round(num%60);
    
      if(d>0){
        return(d + " days, " + h + " hours, "+m+" minutes");
      }else{
        return(h + " hours, "+m+" minutes");
      }
    }
    
    var input1 = 68.68
    console.log(ConvertMinutes(input1));
    
    var input2 = 4568.68
    console.log(ConvertMinutes(input2));