JavaScript tip: Finding the total sum of strings with time format (e.g. 00:00:00)

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"

Answer №1

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))

Answer №2

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:

  1. Develop a function that extracts seconds from a duration
  2. Utilize Array.prototype.reduce to find the total seconds from the duration array by using the method created in the first step.
  3. Format the total seconds obtained in step 2 into the desired HH:MM:SS display. Use 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));

Answer №3

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);

Answer №4

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.

Answer №5

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}`)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TypeScript Implementation of ES6 Arrow Functions

Just diving into Typescript, I'm struggling to figure out the solution. I tried researching and looked into destructuring, but still unable to make it work. import React from "react"; import { StyleSheet, Text, View } from "react-native"; const st ...

Press the button to update several span elements

Imagine I have multiple span elements like this: <span>A</span> <span>B</span> <span>C</span> <span>D</span> and a div element (which will be converted to a button later) named "change". <div id="chan ...

Unable to pass on error from Express server to React client app

Background Overview In my project, I've implemented a React component named 'Register.jsx' where users can input their desired username and password. Upon clicking the submit button, this information is transmitted to an Express backend whi ...

Querying data from a label using jQuery

I am facing a challenge with reading label attributes in jQuery. I have multiple labels, each with the same class. These labels contain important information that I need to access. However, despite being able to select the object using $, I am struggling ...

The perplexity regarding asynchronous functions and return statements

I'm attempting to send a request to a Web API and then return true from a function if the input is valid, or false if it's not. I need the request to be asynchronous so that the function doesn't return before the request is verified. While t ...

Displaying a clock using PHP

Seeking a way to display server time on my website, I have successfully implemented client-side time using JavaScript. How can I now showcase the server time? Are there any ZendFramework classes that can assist with this? Currently, I am utilizing the fo ...

Trigger a function when the browser automatically populates an input field

I am attempting to trigger a function that can detect if the browser has autofilled a field and then add a specific class to it. After finding a thread with a solution that mostly works, mentioned here: Here is how I implemented it: $.fn.allchange = fun ...

Incorporating information collected from a modal form into a table using vue.js

insert code hereThis single page application allows users to input data into a modal, which is then automatically added to a table on the main page. var modal = document.getElementById('modalAdd'); var modalBtn = document.getElementById(' ...

What is the best way to manage various versions of JS libraries across different branches?

As a novice developer, I dabble in creating applications for personal use. My go-to tools are the Quasar framework for the front end and Python for the back end. I maintain a git repository where the master branch houses my "production code," but now I am ...

How can I verify if a date is after the current date using Node.js?

I am struggling to set up date validation that ensures the date is after the current date. This is what I have attempted so far: Router.post('/home', [ check('due_date') .isDate() .isAfter(new Date.now()) .wi ...

Improving the Roman Numeral Kata with JavaScript

As a newcomer to the world of coding, I have taken on the challenge of mastering the Roman Numeral Kata using Javascript. I am pleased to report that all the specifications are passing successfully. After refactoring the spec file, I am now focusing on re ...

What causes a TypeError (Invalid response status code) when a 204 response is returned to a fetch() call within a React Server Component?

Take a look at this straightforward Next.js application: https://codesandbox.io/p/sandbox/next-js-app-router-1bvd7d?file=README.md Here is an API route (/api/hello): export default function handler(req, res) { res.status(204).end(); } And there's ...

Use Typescript in combination with React/Redux to showcase a dynamic table on the

Looking to create a React TypeScript Redux application that showcases a table using an API endpoint provided at https://example.com/users The goal is to construct a table with 4 columns: Name, Email, City, and Company, utilizing the API response to popula ...

Transform the default WordPress gallery into a stunning slideshow with FlexSlider 2 integration

Greetings, I am searching for a solution to modify the default WordPress gallery in order to integrate the FlexSlider 2 plugin. I specifically want to incorporate this module or feature from this link, but I have been unable to figure it out myself. Your ...

What is the best way to send a custom property through Vue router?

I'm currently working with a route instance: const router = new Router({ routes: [ { path: '/', name: 'Home', component: MainContainer, redirect: '/news/list', children: [ { ...

The universal CSS variables of Material UI

Creating reusable CSS variables for components can greatly simplify styling. In regular CSS, you would declare them like this: :root { --box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.3); } This variable can then be utilized as shown below: .my-class { ...

Enhancing Application Performance Through Next.js Development

I'm currently working on an application using next.js and I am looking to implement code splitting in order to reduce the bundle size and load pages on demand. Unfortunately, I have not been able to find a way to do this without specifying routes. Fo ...

(Spotify Web API) Issue with Creating New Playlist - Received Error 403 (Forbidden) upon POST request

Looking for guidance on creating a new playlist using the Web API? Check out the notes here: When making a POST request to https://api.spotify.com/v1/users/{user_id}/playlists, make sure you include the access token and data with a content type of 'a ...

Achieving a smooth transition from a blur-out effect to a blur-in effect on a background Div

I created a blur in/out effect for my landing page, but it's not functioning as expected and I'm not sure why. It blurs out correctly, but the issue arises when I want the underlying Div to fade in. Currently, it just appears abruptly after the ...

Synchronizing the call of various views in an Angular application

I'm currently working on an angular single page application with a specific structure in mind. "app.parent - main parent state" "app.parent.childState - child state" "app.parent.childSatate" includes 4 different named views. My goal is to display so ...