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; // (or alternatively) h = String(h).padStart(2, '0')
m = m < 10 ? '0' + m : m; // (or alternatively) m = String(m).padStart(2, '0')
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"
👍 Very short code for transferring minutes in two formats!
let format1 = (n) => `${n / 60 ^ 0}:` + n % 60
console.log(format1(135)) // "2:15"
console.log(format1(55)) // "0:55"
let format2 = (n) => `0${n / 60 ^ 0}`.slice(-2) + ':' + ('0' + n % 60).slice(-2)
console.log(format2(135)) // "02:15"
console.log(format2(5)) // "00:05"