Open In App

JavaScript Program to Convert Hours into Seconds

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Hours and Seconds are units of time. These units are essential for managing schedules, planning activities, and organizing daily routines. Here we will convert hours into seconds using JavaScript.

Example:

// Formula to convert hours into seconds
1 hour = 1*60 * 60 seconds

Below are the approaches for converting hours into seconds in JavaScript:

Table of Content

Using Function

In this approach, the code defines a function, convertHoursToSeconds, that takes the hours as an input parameter for converting it into seconds units. It then invokes the function with an hour value of 4. Inside the function, use the formula: hours*60*60, to convert it into seconds. Finally, return the result.

Example: The example below shows the demonstration of converting hours into seconds using a function.

JavaScript
function convertHoursToSeconds(hours) {
    return hours * 60 * 60;
}

const hours = 4;
const seconds = convertHoursToSeconds(hours);
console.log("Seconds:", seconds);

Output
Seconds: 14400

Time Complexity: O(1)

Space Complexity: O(1)

Using Class

In this approach, we will define a class named TimeConverter which will contain a method called convertToSeconds and will handle the conversion of hours to seconds. Instantiate the TimeConverter class using the new keyword, which creates an object of the class. Call the convertToSeconds method on the converter object, passing the number of hours you want to convert as an argument. Print result.

Example: The example below shows the demonstration of converting hours into seconds using class.

JavaScript
class TimeConverter {
    convertToSeconds(hours) {
        return hours * 60 * 60;
    }
}

const converter = new TimeConverter();
const hours = 4;
const seconds = converter.convertToSeconds(hours);
console.log("Seconds:", seconds);

Output
Seconds: 14400

Time Complexity: O(1)

Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads