Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Hours and minutes from number of seconds using JavaScript
We are required to write a JavaScript function that takes in the number of seconds and returns the number of hours and minutes contained in those seconds.
Problem Statement
Given a number of seconds, we need to convert it into a readable format showing hours and minutes.
Input:
3601 seconds
Expected Output:
"1 hour(s) and 0 minute(s)"
Solution
Here's how we can convert seconds to hours and minutes:
const seconds = 3601;
const toTime = (seconds = 60) => {
const hR = 3600; // 1 hour = 3600 seconds
const mR = 60; // 1 minute = 60 seconds
let h = Math.floor(seconds / hR);
let m = Math.floor((seconds - (h * 3600)) / mR);
let res = `${h} hour(s) and ${m} minute(s)`;
return res;
};
console.log(toTime(seconds));
1 hour(s) and 0 minute(s)
How It Works
The conversion uses these calculations:
-
Hours: Divide total seconds by 3600 and use
Math.floor()to get whole hours - Minutes: Get remaining seconds after removing hours, then divide by 60
Alternative Approach
Here's a more flexible version that handles different time units:
const convertSeconds = (totalSeconds) => {
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const remainingSeconds = totalSeconds % 60;
return {
hours: hours,
minutes: minutes,
seconds: remainingSeconds,
formatted: `${hours}h ${minutes}m ${remainingSeconds}s`
};
};
// Test with different values
console.log(convertSeconds(3661)); // 1 hour, 1 minute, 1 second
console.log(convertSeconds(7200)); // 2 hours exactly
console.log(convertSeconds(90)); // 1 minute, 30 seconds
{ hours: 1, minutes: 1, seconds: 1, formatted: '1h 1m 1s' }
{ hours: 2, minutes: 0, seconds: 0, formatted: '2h 0m 0s' }
{ hours: 0, minutes: 1, seconds: 30, formatted: '0h 1m 30s' }
Conclusion
Converting seconds to hours and minutes involves dividing by 3600 for hours and using the modulo operator for remaining time. Use Math.floor() to ensure whole numbers for time units.
Advertisements
