Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript: 13.19 to "1:11 PM"
var to12Hr = function(n, r /* round to nearest r minutes */) {
if (!n || n >= 24) return '12:00 AM';
var m = (Math.round(n%1 * (r = (r ? 60/r : 60))) / r) * 60 | 0;
return ((n = (m>59 ? n+1 : n))>=13 ? (n|0)-12 : n|0) + ':' + (m>9 ? (m>59 ? '00' : m) : '0'+m) + (n>=12 && m<60 ? ' PM' : ' AM');
}
// to12Hr(6.5) => "6:30 AM"
// to12Hr(13.19) => "1:11 PM"
// to12Hr(13.19, 15) => "1:15 PM" (rounds to 15 mins)
// Useful for jQuery sliders and things.
@UPlanMe

This comment has been minimized.

Copy link

@UPlanMe UPlanMe commented Dec 1, 2011

I would suggest using the following for line 3:
var m = Math.round(((n%1_(r = (r ? 60/r : 60)))/r)_60);

This is because for a decimal value like 16.516666666666666 the result of your code is 31.000000000000004 when it should be 31.

@redoPop

This comment has been minimized.

Copy link
Owner Author

@redoPop redoPop commented Dec 1, 2011

Good catch; thanks for pointing this out!

Your own solution works fine in all cases where r is falsy or 1, but otherwise causes the function to ignore rounding, so I've abused a bitwise OR to floor the final result instead.

@UPlanMe

This comment has been minimized.

Copy link

@UPlanMe UPlanMe commented Dec 1, 2011

Wooo, slick!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment