Skip to content Skip to sidebar Skip to footer

How To Format Decimal Hours Greater Than 24 Hours Into Hours Minutes In Javascript

I have seen many posts about decimal hours to hours:minutes, but I have not found any that work for more than a days worth. I am using the following with moment.js.. function forma

Solution 1:

I have no idea what Moment.js is and I am not sure what you are trying to achieve exactly. However, if I understand it well, you want to be able to convert decimal hours, going as high as you want, into a date.

I can propose you this code:

functionformatHours(decimalHours) {

    let minutes = decimalHours % 1;
    let hours = decimalHours - minutes;
    minutes *= 60;
    minutes = Math.round(minutes);

    if (hours > 24) {

        var day = Math.floor(hours / 24);
        hours %= 24;

    }

    let date = newDate();
    date.setHours(hours);
    date.setMinutes(minutes);

    if (day) {

        date.setDate(day);

    }

    console.log(`${date}`);

}

formatHours(24.88);

This will handle any decimal input up to 672.00 (28*24), you can just improve it to handle month and so on.

Solution 2:

As commenter asked, what format are you looking for?

I would recommend adding moment-duration-format plugin which seems to be written just for your usecase. Then you could simply write:

functionformatHours(decimalHours) {
  return moment.duration.format(hoursDecimal, 'hours').format('D:HH:mm');
};

Solution 3:

// This is for moment.js in angular

list : any = ["9:12","4:35","9:11"]; // declare properly

for(var i=0 ; i < 3; i++){
    var parts = this.list[i].split(":");;
    var hours =  parseInt(parts[0]) ;
    var minutes = parseInt(parts[1]); 
    this.a = moment.duration(this.a._data.hours,'hours').add(hours,'hours').add(this.a._data.minutes,'minutes').add(minutes,'minutes');
  }
  var totalHours = (24 * this.a._data.days) + this.a._data.hours ;
  var total = totalHours + ":" +this.a._data.minutes; 
  }

Post a Comment for "How To Format Decimal Hours Greater Than 24 Hours Into Hours Minutes In Javascript"