Differences in time displayed as hh:mm format

My current challenge involves calculating the time difference using a specific function:

const calcTimeDiff = (time1: string, time2: string) => {
    const timeStart = new Date()
    const timeEnd = new Date()
    const valueStart = time1.split(':')
    const valueEnd = time2.split(':')

    timeStart.setHours(+valueStart[0], +valueStart[1], 0, 0)
    timeEnd.setHours(+valueEnd[0], +valueEnd[1], 0, 0)

    const difference = timeEnd.getTime() - timeStart.getTime()
    return format(difference, 'HH:mm') // date-fns
}

I provided calcTimeDiff('08:45', '16:00') as an example where the expected output is 07:15. Surprisingly, I am getting 08:15. My suspicion leans towards timezone discrepancies causing this discrepancy.

In my attempt to debug the code, I came across the following findings:

console.log(difference, timeStart, timeEnd)
Thu Jan 01 1970 08:15:00 GMT+0100, Wed Aug 17 2022 08:45:00 GMT+0200, Wed Aug 17 2022 16:00:00 GMT+0200

Answer №1

Utilize the built-in intervalToDuration method available in the date-fns library to simplify your code. This function will provide you with an object containing information such as years, months, days, and hours.

{years: 0, months: 0, days: 0, hours...}

You can easily integrate this into your existing function like this:

const calculateTimeDifference = (time1: string, time2: string) => {
    const startTime = new Date()
    const endTime = new Date()
    const startValues = time1.split(':')
    const endValues = time2.split(':')

    startTime.setHours(+startValues[0], +startValues[1], 0, 0)
    endTime.setHours(+endValues[0], +endValues[1], 0, 0)

    return intervalToDuration({ start: startTime, end: endTime })
}

Answer №2

When dealing with time strings in the format hh:mm, there is no need to use the Date object. Simply perform the following calculation:

const calcTimeDifference = (time1: string, time2: string) => {
  const [h1, m1] = time1.split(':');
  const [h2, m2] = time2.split(':');
  let diff = (h2 - h1) * 60 + (m2 - m1);
  if (diff < 0) diff += 24 * 60;
  const hours = Math.floor(diff / 60);
  const minutes = diff - hours * 60;
  const hh = hours.toString().padStart(2, '0');
  const mm = minutes.toString().padStart(2, '0');
  return `${hh}:${mm}`;
}

Answer №3

I concur with @eugene and believe that is the correct approach. However, if you require an answer in the format of your current code, here is a sample:

function calculateTimeDifference(startTime, endTime) {
    const timeStart = new Date()
    const timeEnd = new Date()
    const startTimeValues = startTime.split(':')
    const endTimeValues = endTime.split(':')

    timeStart.setHours(+startTimeValues[0], +startTimeValues[1], 0, 0)
    timeEnd.setHours(+endTimeValues[0], +endTimeValues[1], 0, 0)

    let difference = new Date();
    difference.setHours(timeEnd.getHours() - timeStart.getHours())
    difference.setMinutes(timeEnd.getMinutes() - timeStart.getMinutes())
    return console.log(difference, timeStart, timeEnd) // utilizing date-fns library
}
calculateTimeDifference('08:45', '16:00');

If you continue generating a date object based on the time difference in your code, it will result in an arbitrary time.

Answer №4

This is how I tackled the problem:

function calculateTimeDifference(start: string, end: string) {
    const startTime = new Date()
    const endTime = new Date()
    const startValues = start.split(':')
    const endValues = end.split(':')

    startTime.setHours(+startValues[0], +startValues[1], 0, 0)
    endTime.setHours(+endValues[0], +endValues[1], 0, 0)

    const timeDiff = new Date(endTime.getTime() - startTime.getTime())

    return format(
        addMinutes(timeDiff, timeDiff.getTimezoneOffset()),
        'HH:mm'
    )
}

Answer №5

If you want to achieve your desired outcome, try utilizing moment.js.

You can accomplish this by making use of the diff method.

const calculateTimeDifference = (startTime, endTime) => {
    
    const initialTime = moment(startTime, 'HH:mm');   
    const finalTime = moment(endTime, 'HH:mm');   
    
    let difference = finalTime.diff(initialTime);
    return moment.utc(difference).format("HH:mm");
}

console.log(calculateTimeDifference("8:15", "16:15"))
console.log(calculateTimeDifference("7:45", "19:21"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

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

Changing background color using jQuery ID selector

Within thisid, the id of an html element is stored. In order to modify its background color, the code below can be utilized: let thisid = 'test'; $("a#" + thisid).css("background-color", "yellow"); <script src="https://cdnjs.cloudflare.com/a ...

Unable to activate Knockout data-bind using jQuery

I'm developing a plugin using jQuery and knockout.js. Currently, I have a scenario where I need to manipulate radio buttons with knockout data-bindings. However, I've encountered an issue when trying to uncheck a radio button by clicking another ...

The custom hook designed to clear and update time is not functioning as anticipated

After setting the default time using setInterval, it seems to be creating a new instance instead of updating as expected. How can I clear the existing setInterval in the custom hook and set a new value? app.jsx import React from 'react'; import ...

Preventing a JavaScript function from executing multiple times

Having only recently started learning javascript and jquery, I encountered a problem where one of my functions kept executing itself when calling another function. Despite trying various solutions found here, the function either stopped executing altogethe ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

Issues encountered when attempting to send a JSON object from Javascript to a Servlet using AJAX

I've been attempting to send a JSON object to a servlet using AJAX, but I'm running into an issue where the object is showing up as null in the servlet. Can't seem to pinpoint the problem in this code. JAVASCRIPT function submitValues(even ...

What is the best way to view an image stored in a database in a separate window?

I am currently working on a page that displays multiple images, with each image's path stored in the database. Using PHP, I retrieve and display these images based on their paths. My goal is to enable users to click on an image and have it open in a ...

Set the new cloned div to be read-only within the dialog box

I have customized a div on a webpage that I want to display as a preview in a dialog box using jQuery's clone function. Now I am trying to make the cloned div readonly once it is displayed in the dialog. Can someone please help me with this? Thank you ...

The flickering problem with HTML5 DOM

I created a HTML5 game using canvas and DOM elements, but I'm facing an issue with flickering DOM elements while playing. The problem seems to be more prevalent in mobile browsers, particularly Chrome. My game includes a full screen canvas with vario ...

Loop through a JSON array in a React Native application

Encountering an issue while working in react native involving parsing a JSON object and iterating over a nested array. The goal is to list all profiles objects. Tried the code below but it's not fetching the profiles object. How can I print all profi ...

I do not intend for my JavaScript code to be echoed in PHP

I have encountered an issue with an ads script that I saved in my database using a textarea field. However, when I try to echo this script in PHP, it does not work as expected. Below is the script that I stored in the database: <script type="text/javas ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

Combatting repetitive code through the use of Redux toolkit and actions

My code is currently long and repetitive. I realize that using helper functions would help me cut it down and make it more maintainable and readable. As a React beginner, I have a question: Should I implement most of this logic with helper functions in a s ...

Managing ajax requests for lazy loading while scrolling through the middle of the window can be a challenging task. Here are some tips on

I have implemented Lazy loading in my Project. I found a reference at which explains how to make an ajax call after scrolling and image upload with slow mode without allowing scrolling until the loader is shown. The code snippet I am using is as follows: ...

What steps are required to transform a TypeScript class with decorators into a proper Vue component?

When I inquire about the inner workings of vue-class-component, it seems that my question is often deemed too broad. Despite examining the source code, I still struggle to grasp its functionality and feel the need to simplify my understanding. Consider th ...

Issue with document.Form.submit not working in combination with window.location in Chrome and some versions of IE 7 and 8

Hey there, I'm currently working on a project that involves conducting surveys. Each page of the survey presents a new question for the user to answer, and upon submission, the user is redirected to the next question. The javascript code below allows ...

Perform an addition operation on two numerical values within an AJAX function

Hello, I am a beginner in ajax and I am attempting to sum two numbers within an ajax function. Here is the code snippet that I am using: $("#next_btn").click(function(){ Display_Load(); var page = this.title; var subtract = 1; $("#content" ...

What is the method for changing the Uint8Array object into a string?

I am encountering a similar issue as the one discussed in this post. I have read the solution provided, but I am having trouble grasping how to implement it. Are there any alternative suggestions? Here is my code snippet: var eccrypto = require("eccrypto ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

Interactive calendar feature displaying events upon hovering over a date

I need some assistance with displaying a drop-down list on full calendar events when hovering over the events. Can someone provide guidance? Here is a glimpse of what I currently have: https://i.sstatic.net/fZXMH.png I've attempted setting the z-in ...