Convert Minutes to Hours and Minutes in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 20, 2022

banner

Check out my new book

Convert Minutes to Hours and Minutes in JavaScript #

To convert minutes to hours and minutes:

  1. Get the number of full hours by dividing the minutes by 60.
  2. Get the remainder of minutes.
  3. Optionally, format the hours and minutes as hh:mm.
index.js
function toHoursAndMinutes(totalMinutes) { const minutes = totalMinutes % 60; const hours = Math.floor(totalMinutes / 60); return `${padTo2Digits(hours)}:${padTo2Digits(minutes)}`; } function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(toHoursAndMinutes(90)); // 👉️ 01:30 console.log(toHoursAndMinutes(60)); // 👉️ 01:00 console.log(toHoursAndMinutes(115)); // 👉️ 01:55

We created a reusable function, which takes a number that represents the total minutes as a parameter and converts them to hours and minutes.

The first step is to get the number of full hours, by dividing the total minutes by 60 and rounding the result down.

The Math.floor function, rounds a number down if the number has a decimal, otherwise it returns the number as is.

index.js
console.log(Math.floor(3.99)); // 👉️ 3 console.log(Math.floor(3.01)); // 👉️ 3 console.log(Math.floor(3)); // 👉️ 3
This ensures we don't get values with a decimal, e.g. 1.336 for the hours. If the value has a decimal, we want to show the minutes and hide the decimal.

We used the modulo (%) operator to get the remainder of minutes.

index.js
console.log(90 % 60); // 👉️ 30

The example above shows that the remainder of dividing 90 by 60 is 30, in other words, 1 full hour and 30 minutes.

The next step is to format the hours and minutes as hh:mm, e.g. 09:35.

Our padTo2Digits function, takes care of adding a leading zero if the hours or minutes only contain a single digit (are less than 10).

index.js
function padTo2Digits(num) { return num.toString().padStart(2, '0'); } console.log(padTo2Digits(3)); // 👉️ '03' console.log(padTo2Digits(6)); // 👉️ '06' console.log(padTo2Digits(10)); // 👉️ '10'

We want to make sure the result does not alternate between single and double digit values depending on the hours and minutes.

The example from the code snippet formats the values as hh:mm, but you could tweak this depending on your use case.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.