There are a couple parts to this question. I am not opposed to using a jQuery plugin if anyone knows of one that will accomplish what I want done.
Q1 - How do I convert minutes into hours and vise versa? For example how would I convert 90 minutes into 1 hour and 30 minutes. In the code below how would I get "totalMin" converted and displayed in "convertedHour" and "convertedMin"?
HTML:
<span class="totalMin">90</span> Minutes <span class="convertedHour">0</span> Hours <span class="convertedMin">0</span> Minutes
jsFiddle: http://jsfiddle.net/ExFBD
Q2 - How would I add up a group of time slots? For example, How would I add 1 hour 30 mins, 2 hours 45 mins and 2 hour 15 mins together?
HTML:
<span class="hour-1 hour">1</span> hour <span class="min-1 min">30</span> min <span class="hour-2 hour">2</span> hour <span class="min-2 min">45</span> min <span class="hour-3 hour">2</span> hour <span class="min-3 min">15</span> min <span class="totalHour">0</span> hour <span class="totalMin">0</span> min
jsFiddle: http://jsfiddle.net/DX9YA/
Q3 - How would I take a time value (3 hours and 30 mins) and add it to a real time stamp such as 10:30 AM? How would I take AM vs PM into account?
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));
int hours = t / 60; //since both are ints, you get an int int minutes = t % 60; System. out. printf("%d:%02d", hours, minutes);
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}`; }
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