Member-only story
Converting between units of time is a common need when writing JavaScript code. Being able to easily translate hours into seconds can be extremely useful for timing events, displaying time values, calculating intervals, and more.
In this quick tutorial, you’ll learn a simple way to convert hours to seconds in JavaScript.
The key is using JavaScript’s powerful Date API. Here is a function that handles the conversion:
function hoursToSeconds(hours) {
return hours * 3600;
}
To break this down:
- We accept the number of hours as a parameter called
hours
- There are 3600 seconds in an hour (60 secs * 60 mins)
- So we simply multiply the
hours
by 3600 to get the total seconds - Return the result
For example:
hoursToSeconds(2); // 7200
hoursToSeconds(0.5); // 1800
The key takeaways here are:
- Use multiplication to convert between units
- Know your conversions (3600 seconds per 1 hour)
- Functions allow reusable and clean code
Being able to convert time units will unlock all kinds of helpful functionality in your JavaScript projects. Mastering simple helpers like hoursToSeconds
will pay dividends.
Give it a try in your codebase and see how it goes.