Change getHours to 12 Hour Format in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

banner

Photo by Matt Heaton

Change getHours to 12 Hour Format #

To change the getHours() method to a 12 hour format:

  1. Use the modulo % operator to get the remainder of dividing a call to the getHours() method by 12.
  2. If the remainder is greater than zero, then return the remainder.
  3. If the remainder is equal to zero, 12 should be returned.
index.js
function formatHoursTo12(date) { return date.getHours() % 12 || 12; } const date1 = new Date('September 24, 2025 15:24:00'); console.log(formatHoursTo12(date1)); // ๐Ÿ‘‰๏ธ 3 const date2 = new Date('September 24, 2025 23:05:00'); console.log(formatHoursTo12(date2)); // ๐Ÿ‘‰๏ธ 11 const date3 = new Date('September 24, 2025 12:13:00'); console.log(formatHoursTo12(date3)); // ๐Ÿ‘‰๏ธ 12

We used the remainder (%) operator to get the remainder of dividing the hours by 12.

If the hours are less than 12, then the number of hours will be returned directly.

index.js
console.log(3 % 12); // ๐Ÿ‘‰๏ธ 3 console.log(11 % 12); // ๐Ÿ‘‰๏ธ 11

However, if the hours are more than 12, we return the remainder to get a 12 hour format.

index.js
console.log(13 % 12); // ๐Ÿ‘‰๏ธ 1 console.log(16 % 12); // ๐Ÿ‘‰๏ธ 4 console.log(22 % 12); // ๐Ÿ‘‰๏ธ 10

The last step is to handle the edge case where the hours are 12 or 24, because there would be no remainder if we divide either number by 12.

index.js
console.log(12 % 12); // ๐Ÿ‘‰๏ธ 0 console.log(24 % 12); // ๐Ÿ‘‰๏ธ 0

We used the logical OR (||) operator, which returns the value to the left if it's truthy, otherwise it returns the value to the right.

Truthy are all values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

Because 0 is a falsy value, if the remainder of the division is 0, we will return the value to the right of the OR (||) operator, which is 12.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee