snippetjavascriptMinor
Convert number into hours : minutes
Viewed 0 times
numberconvertintohoursminutes
Problem
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.
So this turns something like 53.34 into "53:20"
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"
Solution
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
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:
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);
};Code Snippets
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);
};Context
StackExchange Code Review Q#74894, answer score: 7
Revisions (0)
No revisions yet.