# Convert number into hours : minutes

I wrote a simple extension to convert a number into a hours and minutes string in the ##:## format. This seems like a good way to do it, but let me know what you think.

Number.prototype.display_hours_minutes = function () {
var remainder = this % 1;
var remainderTime = new Date(remainder * 3600 * 1000);
return ('0' + Math.floor(this)).slice(-2) + ':' + ( '0' + remainderTime.getMinutes()).slice(-2);
};


So this turns something like 53.34 into "53:20"

• This edited content can probably be a self-answer instead. – Jamal Dec 26 '14 at 23:28

Extending built-in types always carries a risk that your code will interact poorly with other code. Often, web page authors cobble together pages that use many JavaScript libraries. Consider making it a regular function.

The function has a silent cap of "99:59". That's an odd limit. Either the number of hours should be unlimited, or it should be modulo 24. Modulo 100 is totally unexpected.

The code would also fail to output the minutes correctly in some non-standard time zones, such as India, where the time zone offset relative to UTC is not an integral number of hours.

You don't need to compute remainder, as the Date object takes care of extracting the minutes portion in any case.

It took me a few seconds to figure out the significance of 3600 and 1000. A comment would be helpful.

Here's my recommendation for a modulo 24 solution:

Number.prototype.display_hours_minutes = function () {
var date = new Date(this * 3600 /* sec per hr */
* 1000 /* msec per sec */);
return ('0' + date.getUTCHours()  ).slice(-2) + ':' +
('0' + date.getUTCMinutes()).slice(-2);
};

• I removed the truncation of the hours over 99 in my last edit as you mentioned. I also tried the code you posted and it doesn't seem to calculate correctly, or at least not how I am wanting it to. Here is an example: plnkr.co/edit/bzf8C3boaajaAC9ErnUI?p=preview – Geo242 Dec 26 '14 at 23:30
• Extending Number.prototype might not even be possible in the future; the standards committee has often flirted with the idea of making built-in classes sealed. – fluffy Dec 26 '14 at 23:31
• Actually, we just exposed a latent bug in your original code as well! date.getMinutes() interprets date in local time, which is wrong. Fixed in Rev 2. – 200_success Dec 27 '14 at 3:59
• I think that maybe your code is solving a different problem than the one that my code is solving. In the example I gave above, where I have the number 53.34 hours. I want to convert that into 53 hours and 20 minutes in the string representation of "53:20". The code you posted above turns 53.34 into "05:20", which is not what I need. My original code works well for what I need (minus the truncation of numbers over 99, which I thank you for pointing out). – Geo242 Dec 28 '14 at 1:14
• If you didn't want modulo 12 or modulo 24, then why would you want zero-padding? – 200_success Dec 28 '14 at 1:17