I have an array that contains time values:
// hours, minutes, seconds
let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
Is there a way to calculate the total sum of these elements?
output: "06:30:55"
I have an array that contains time values:
// hours, minutes, seconds
let arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
Is there a way to calculate the total sum of these elements?
output: "06:30:55"
Here is the solution you can try out:
def sum_time(arr):
total_seconds = 0
for time in arr:
h, m, s = map(int, time.split(':'))
total_seconds += h * 3600 + m * 60 + s
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
return f'{hours:02d}:{minutes:02d}:{seconds:02d}'
time_list = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
print(sum_time(time_list))
To simplify the process, convert your array of durations into seconds, sum them to calculate total seconds, and then format the total seconds into the HH:MM:SS style you prefer.
Follow these steps:
Array.prototype.reduce
to find the total seconds from the duration array by using the method created in the first step.String.prototype.padStart()
for achieving a two-digit output per time unit.Here's an example of how this can be done:
const arr = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
/**
* @method
* Pads a number with zeros to ensure two digits
*/
function padNumber(num) {
return num.toString().padStart(2, '0');
}
/**
* @method
* Calculates the total seconds from a duration in HH:MM:SS format
*/
function getSecondsFromDuration(duration) {
const [hours, minutes, seconds] = duration.split(':').map(n => +n);
return hours * 60 * 60 + minutes * 60 + seconds;
}
/**
* @method
* Formats the duration in seconds into HH:MM:SS string
*/
function getDurationFromSeconds(seconds) {
const hours = Math.floor(seconds / 3600);
seconds -= hours * 3600;
const minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
return `${padNumber(hours)}:${padNumber(minutes)}:${padNumber(seconds)}`;
}
const totalSeconds = arr.reduce((acc, cur) => {
return acc + getSecondsFromDuration(cur);
}, 0);
console.log(getDurationFromSeconds(totalSeconds));
If you're looking to convert an array of time values into seconds and then rebuild as a new string with smaller units, this code snippet can help you achieve that:
let timeArray = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"],
factors = [3600, 60, 1],
totalSeconds = timeArray.reduce((seconds, currentTime) => currentTime.split(':').reduce((accumulatedSeconds, timeUnit, index) => accumulatedSeconds + timeUnit * factors[index], seconds), 0),
formattedResult = factors.map(factor => {
const value = Math.floor(totalSeconds / factor);
totalSeconds -= value * factor;
return value.toString().padStart(2, '0');
}).join(':');
console.log(formattedResult);
let timeArray = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"]
let hours = 0, minutes = 0, seconds = 0;
timeArray.map((value, index) => {
hours = hours + +value.split(":")[0];
minutes = minutes + +value.split(":")[1];
seconds = seconds + +value.split(":")[2];
})
console.log(hours + ":" + minutes + ":" + seconds)
If you add a +
in front of it, the value will be converted into a Number for calculation.
To add up and convert your time values to a Date, you can utilize the combination of map
and reduce
:
const result = ["00:00:30", "00:20:00", "01:00:10", "05:10:15"].map(value => {
const temp = value.split(":")
return (+temp[0]) * 60 * 60 + (+temp[1]) * 60 + (+temp[2])
}).reduce((accumulator, currentValue) => accumulator + currentValue)
const newDate = new Date(result*1000)
const minutesValue = newDate.getMinutes();
const hoursValue = newDate.getHours()-1; // subtracting 1 for accurate time
const secondsValue = newDate.getSeconds();
console.log("Total Duration: ", `${hoursValue}:${minutesValue}:${secondsValue}`)
Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...
My current task involves fetching data via AJAX and then using a for-loop and if-statement to determine which goods belong in each shopping cart. Once identified, I need to display these goods in separate tables corresponding to each customer. Although the ...
Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...
While I am incorporating Nightmare actions in my script, a question arises regarding the use of the wait function within the evaluate_now function. How can I utilize the wait function within the evaluate_now function? I am aware that I can simply use the ...
Similar Question: Unable to get jquery tabs nested I am trying to create a nested tab, but haven't found a satisfactory solution through my research. Can anyone provide me with some guidance? I have limited experience in JavaScript or jQuery prog ...
Similar questions have been asked in the past, but I still haven't found a solution to my specific inquiry. Here it is: I have a table that needs to be sortable using a JavaScript plugin like ListJS. The key requirement is that I must have only one & ...
I am trying to implement a tabs control using jQuery. Here is the HTML code I have: <div id="tabs" class="news1"> <ul> <li><a href="#tabs-1">Track</a></li> <li><a href="#tabs-2">History&l ...
I am currently running a Node.js app with Express that is deployed on OpenShift. I have set up databases using the PHPMyAdmin 4.0 cartridge. Although I can establish a connection to the database, anytime I run a query, it throws an ECONNREFUSED error. Whe ...
I am using a directus API to fetch data, which is returned in an array of objects. I can render the array or an object from it, but not when trying to access a property of the object <template> <div class="grid grid-cols-2 gap-6 mt-6&quo ...
Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...
Hey there! I'm currently tackling a web project that involves incorporating two form tags on one page, each with its own distinct purpose. Nevertheless, it appears that the inner form tag isn't behaving as it should. My suspicion is that this iss ...
Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...
I am currently working on a walkthrough video where the user has the ability to slide a UI slider across the screen, causing the camera to navigate through a 3D space. The video itself has been exported in jpg frames, numbered from 0 to 350.jpg. My appro ...
Currently in the process of developing my Ecommerce project, I have successfully created a product grid with links to each specific product. However, I am facing an issue where I am unable to view the data of each individual item. Below is the code for my ...
Today has been dedicated to troubleshooting and searching for a solution regarding the integration of TouchWipe () on a custom one-page-site script based on Parallax that I found perfect for my latest project (). The script itself performs beautifully wit ...
When attempting to run some JavaScript code on the Chrome driver, I encountered a JavascriptException. Despite my confidence in the correctness of the JS code, the following error message was displayed: raise exception_class(message, screen, stacktrace) s ...
I currently have a program that executes an algorithm processing real-time data. Once per hour, the algorithm's parameters are optimized based on new historical data. Currently, this optimization process is running in a single thread, pausing the rea ...
I'm attempting to embed an HTML page within a div and then individually select all the img tags within that page to display an overlay div on top of the images. Currently, I can insert the HTML into a div named "asd" and it seems like the jQuery is f ...
After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...
I am currently in the process of developing an SDK that will soon be available on npm. One of the requirements for this SDK is to deliver its version to the client. My goal is to have this version match the one specified in the package.json file. However ...