Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Wed May 24 2023

How to convert time in JavaScript

In this guide, we will do some time conversion. We will learn to convert seconds, minutes and hours between themselves.

So basically, if we want to know how many seconds 2 hours and 5 minutes is, our functions should be able to calculate that.

Formula

The formula for this is quite straight forward, let's have a look

seconds = minutes * 60 seconds = hours * 3600 minutes = seconds / 60 minutes = hours * 60 hours = minutes / 60 hours = seconds / 3600

Our functions

And to translate this into code, it will look something like this

const convertToSeconds = (minutes = 0, hours = 0) => { return minutes * 60 + hours * 3600; }; const convertToMinutes = (seconds = 0, hours = 0) => { return seconds / 60 + hours * 60; }; const convertToHours = (seconds = 0, minutes = 0) => { return seconds / 3600 + minutes / 60; };

Our functions will be prepared for accepting both of the other units. The reason why we are setting each to default as 0 is to make sure it is a number that is comming in, since multiplying with undefined will result in NaN.

Test our functions

Let's run some tests on our functions

console.log(convertToSeconds(0, 5)); // 18000 console.log(convertToSeconds(3, 10)); // 36180 console.log(convertToMinutes(120, 5)); // 302 console.log(convertToMinutes(300, 0)); // 5 console.log(convertToHours(3600)); // 1 console.log(convertToHours(3600, 120)); // 3

All right, seems to be working fine!

Outro

In this short guide, we showed how to convert time between seconds, minutes and hours. This can be quite useful when working with dates and different types of timestamps.

I hope you enjoyed this guide, and thanks for reading!

signatureWed May 24 2023
See all our articles