Skip to content

Instantly share code, notes, and snippets.

@seanghay
Last active November 4, 2022 08:15
Show Gist options
  • Select an option

  • Save seanghay/0aff1e3f276f724b267dbd06643ebdce to your computer and use it in GitHub Desktop.

Select an option

Save seanghay/0aff1e3f276f724b267dbd06643ebdce to your computer and use it in GitHub Desktop.

Revisions

  1. seanghay revised this gist Nov 4, 2022. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions 24-time.js
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,6 @@

    /**
    * 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.
  2. seanghay created this gist Nov 4, 2022.
    14 changes: 14 additions & 0 deletions 24-time.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    /**
    * 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'