Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting minutes to hours (H:mm) in MomentJS

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');
like image 238
Addy Avatar asked Apr 24 '18 12:04

Addy


People also ask

How do I get time from MomentJS?

You can directly call function momentInstance. valueOf(), it will return numeric value of time similar to date. getTime() in native java script.

How do you convert minutes to hours in typescript?

JavaScript Code: function timeConvert(n) { var num = n; var hours = (num / 60); var rhours = Math. floor(hours); var minutes = (hours - rhours) * 60; var rminutes = Math. round(minutes); return num + " minutes = " + rhours + " hour(s) and " + rminutes + " minute(s)."; } console. log(timeConvert(200));

What does format () do in moment?

format(); moment(). format(String); This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.

How do you find moments from minutes?

The moment(). minute() Method is used to get the minutes from the current time or to set the minutes. moment(). minutes();


2 Answers

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)
like image 83
sridhar.. Avatar answered Sep 20 '22 08:09

sridhar..


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

like image 36
kewlashu Avatar answered Sep 21 '22 08:09

kewlashu