Cody
Cody

Reputation: 919

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));

Upvotes: 3

Views: 9783

Answers (4)

DCR
DCR

Reputation: 15665

//minutes to hour converter
    function ConvertMinutes(num){
      h = Math.floor(num/60);
      d = Math.floor(h/24);
      h = h - d * 24
      m = Math.floor(num%60)
      s = ((input - d*24*60 - h*60 -m)*60).toFixed(2)
      
      return('days: '+ d + ', hours: '+ h + ', minutes: ' +m+', seconds: '+s);
    }

    var input = 4568.68

    console.log(ConvertMinutes(input));

Upvotes: 2

k-kundan
k-kundan

Reputation: 46

function secondsToString(hours)
{
var seconds = hours * 60 * 60;

var numdays = Math.floor(seconds / 86400);

var numhours = Math.floor((seconds % 86400) / 3600);

var numminutes = Math.floor(((seconds % 86400) % 3600) / 60);

var numseconds = ((seconds % 86400) % 3600) % 60;

return numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";

}

Upvotes: -1

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

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));

Upvotes: 14

Christos
Christos

Reputation: 53958

By refactoring a bit your code, you could try something like the following:

function ConvertMinutes(num){
    days = Math.floor(num/1440);
    hours = Math.floor((num%1440)/60);
    minutes = (num%1440)%60;
    return {
        days: days,
        hours: hours,
        minutes: minutes
    };
}

var input = 68.68

console.log(ConvertMinutes(input));

Upvotes: 0

Related Questions