How to format decimal hours greater than 24 hours into hours minutes in JavaScript

前提是你 提交于 2020-01-07 04:48:08

问题


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 formatHours(decimalHours) {
    var duration = moment.duration(decimalHours, 'hours');

    var hours = duration.hours();
    var minutes = duration.minutes();

    var date = moment().hours(hours).minutes(minutes);
    var result = date.format('HH:mm');

    return result;
  }

but this does not work for greater than 24 hours,eg I have a hours coming in representing over a year.

Is there a ways to handle this, and also format for the current locale (as moment should do)

Thanks in advance for any help


回答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:

function formatHours(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 = new Date();
    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.




回答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:

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



回答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; 
  }


来源:https://stackoverflow.com/questions/43042337/how-to-format-decimal-hours-greater-than-24-hours-into-hours-minutes-in-javascri

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!