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');
You can directly call function momentInstance. valueOf(), it will return numeric value of time similar to date. getTime() in native java script.
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));
format(); moment(). format(String); This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
The moment(). minute() Method is used to get the minutes from the current time or to set the minutes. moment(). minutes();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With