Skip to content

Instantly share code, notes, and snippets.

@seanghay
Last active November 4, 2022 08:15
Show Gist options
  • Save seanghay/0aff1e3f276f724b267dbd06643ebdce to your computer and use it in GitHub Desktop.
Save seanghay/0aff1e3f276f724b267dbd06643ebdce to your computer and use it in GitHub Desktop.
/**
* Note: Not the fastest solution! It's a demo on how to use bitwise operator to avoid branching.
* Convert 24-hour time to 12-hour.
* @returns {string}
* @param {number} a 24-hour number.
*/
function to12time(a) {
return (a - 1) % 12 + 1 + String.fromCharCode(112 - 15 * (a < 12 ^ 0)) + "m"
}
to12time(16)
// => '4pm'
to12time(11)
// => '11am'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment