最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting minutes to hours (H:mm) in MomentJS - Stack Overflow

programmeradmin2浏览0评论

I am trying to add time given by user in minutes to convert them into h:mm format The issue is when total time is <=23:59 momentJS gives proper result but if it increases momentJS changes the day and gives wrong result.

For example if I convert 120 min it gives me 2:00 But in case of 2273 it gives me 13:53

Here is the code

 var totalTimeInMin=2273;
 var totalTimeInHours = moment.utc().startOf('day').add(totalTimeInMin, 'minutes').format('H:mm');

I am trying to add time given by user in minutes to convert them into h:mm format The issue is when total time is <=23:59 momentJS gives proper result but if it increases momentJS changes the day and gives wrong result.

For example if I convert 120 min it gives me 2:00 But in case of 2273 it gives me 13:53

Here is the code

 var totalTimeInMin=2273;
 var totalTimeInHours = moment.utc().startOf('day').add(totalTimeInMin, 'minutes').format('H:mm');
Share Improve this question asked Apr 24, 2018 at 12:12 AddyProgAddyProg 3,05013 gold badges63 silver badges114 bronze badges 1
  • 1 why not use modulo on the total time? – mast3rd3mon Commented Apr 24, 2018 at 12:15
Add a comment  | 

2 Answers 2

Reset to default 14

You can just divide by 60 , to get hours and do modulus for minutes

var totalTimeInMin = 2273;
console.log(Math.floor(totalTimeInMin / 60) + ':' + totalTimeInMin % 60)

Posting late, but I think below details are useful here.

duration from momentjs can also be used for calculating total hours and minutes from a time duration:

function minutes_to_hhmm (numberOfMinutes) {
    //create duration object from moment.duration  
    var duration = moment.duration(numberOfMinutes, 'minutes');
    
    //calculate hours
    var hh = (duration.years()*(365*24)) + (duration.months()*(30*24)) + (duration.days()*24) + (duration.hours());
    
    //get minutes
    var mm = duration.minutes();
    
    //return total time in hh:mm format
    return hh+':'+mm;
}

console.log(minutes_to_hhmm(2273)); // 37:53
console.log(minutes_to_hhmm(220)); //3:40
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.28.0/moment.min.js"></script>

the function minutes_to_hhmm can be easily adapted to other time durations like - hours, days, months etc based on the duration constructor in the documentation

发布评论

评论列表(0)

  1. 暂无评论