Skip to content

Instantly share code, notes, and snippets.

@williammalo williammalo/README.md forked from 140bytes/LICENSE.txt
Last active Oct 2, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Apr 2, 2012

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

@williammalo

This comment has been minimized.

Copy link
Owner Author

commented Apr 2, 2012

@xpansive
Ooh! Clever use of operators!

@williammalo

This comment has been minimized.

Copy link
Owner Author

commented Apr 2, 2012

@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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

commented Apr 3, 2012

@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
You can’t perform that action at this time.