Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 2, 2015 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williammalo/2278451 to your computer and use it in GitHub Desktop.
Save williammalo/2278451 to your computer and use it in GitHub Desktop.
print time

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>
@xpansive
Copy link

xpansive commented Apr 2, 2012

Save 9 bytes
function(h,m){return~-h%12+1+":"+(m>9?"":0)+(h>12?m+" PM":m)}

@williammalo
Copy link
Author

@xpansive
Ooh! Clever use of operators!

@williammalo
Copy link
Author

@xpansive

~-h%12+1 is win!
I tried using h%12, but at noon, it would show "0"... so I just used ?: ...
(h%12||12) would also work, but it's 2 bytes longer.

@xpansive
Copy link

xpansive commented Apr 2, 2012

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.

@maettig
Copy link

maettig commented Apr 3, 2012

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).

@williammalo
Copy link
Author

@maettig quote:"m>9 check is switched"
Oh! Thanks! It's fixed now :)

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