I am new to javaScript, I just coded a method where I can convert a minute to a time in hh:mm AP/PM. I was then displaying the time in a table. I was wondering if there is a better approach to this? Because my code seems quite messy, with many if
and else
statement.
function convertMinsToHrsMin(minutes) {
var str = '';
var h = Math.floor(minutes / 60);
var m = minutes - (h * 60);
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
if (h >= 12) {
if (h == 12) {
str = "PM";
}
else if (h >= 22) {
h = (h - 12);
str = "PM";
}
else {
h = '0' + (h - 12);
str = "PM";
}
}
else {
if (h == 0) {
h = 12;
str = "AM";
}
else {
str = "AM";
}
}
return h + ":" + m + " " + str;
}
startTime = convertMinsToHrsMin(720);
endTime = convertMinsToHrsMin(1080);
alert(startTime);
alert(endTime);
Here is a jsFiddle to work on: https://jsfiddle.net/Issaki1/txns3mhc/