Returns a string that formats time in a smart manner. If minutes is lower than 10, prepend a "0" to the minutes. If hours is in the afternoon, convert it to PM mode.
Thanks to xpansive for minification tips.
function( | |
h, //hours | |
m //minutes | |
) | |
{ | |
return | |
~-h%12+1 //if hours is over 12, subtract 12 | |
+":"+ //add ":" | |
( | |
m>9? //if minutes is smaller than 10 | |
"":0 //prepend a "0" to the minutes | |
) | |
+(h>12?m+" PM":m) //add minutes, and, if in the afternoon, add "PM" | |
} |
function(h,m){return~-h%12+1+":"+(m>9?"":0)+(h>12?m+" PM":m)} |
{ | |
"name": "printTime", | |
"description": "A time formatter. ", | |
"keywords": [ | |
"AM/PM", | |
"time", | |
"hour", | |
"format" | |
] | |
} |
<!DOCTYPE html> | |
<script> | |
printTime = function(h,m){return~-h%12+1+":"+(m>9?"":0)+(h>12?m+" PM":m)} | |
document.write(printTime(new Date().getHours(),new Date().getMinutes())) | |
</script> |
Isn't there a rule that you should display "12:30" during the day but "00:30" during the night? Not sure. May depend on the country. Also, there is a little mistake in your anotated.js (m>9
check is switched).
@maettig quote:"m>9 check is switched"
Oh! Thanks! It's fixed now :)
Thanks! The ~- is basically just like subtracting one, but has different operator precedence so you don't need to use brackets, as you would with (h-1)%12+1.