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
2 Answers
Reset to default 14You 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