How to convert minutes to hours/minutes and add various time values together using jQuery?
Q1:
$(document).ready(function() {
var totalMinutes = $('.totalMin').html();
var hours = Math.floor(totalMinutes / 60);
var minutes = totalMinutes % 60;
$('.convertedHour').html(hours);
$('.convertedMin').html(minutes);
});
Q2:
$(document).ready(function() {
var minutes = 0;
$('.min').each(function() {
minutes = parseInt($(this).html()) + minutes;
});
var realmin = minutes % 60
var hours = Math.floor(minutes / 60)
$('.hour').each(function() {
hours = parseInt($(this).html()) + hours;
});
$('.totalHour').html(hours);
$('.totalMin').html(realmin);
});
In case you want to return a string in 00:00 format...
convertMinsToHrsMins: function (minutes) {
var h = Math.floor(minutes / 60);
var m = minutes % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return h + ':' + m;
}
Thanks for the up-votes. Here's a slightly tidier ES6 version :)
const convertMinsToHrsMins = (mins) => {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.
function display(a){
var hours = Math.trunc(a/60);
var minutes = a % 60;
console.log(hours +":"+ minutes);
}
display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"