Determine the time difference between the beginning and ending times using TypeScript

Is there a way to calculate the difference between the start time and end time using the date pipe in Angular?

 this.startTime=this.datePipe.transform(new Date(), 'hh:mm');
this.endTime=this.datePipe.transform(new Date(), 'hh:mm');

The output looks like this: Start time - 01:14 End time - 01:15

I need to find the time difference between the start and end time. In this case, it should return 1.

If you have any solutions or suggestions, thank you in advance!

Answer №1

If the date is in string format and you are looking to calculate the difference in minutes, you can use the following JavaScript function:

function calculateTimeDifference(startTime, endTime) {
  const start = startTime.split(':');
  const end = endTime.split(':');

  let totalMinDifference = ((parseInt(end[0]) * 60) + parseInt(end[1])) - ((parseInt(start[0]) * 60) + parseInt(start[1]));

  return totalMinDifference; // To get the result difference in seconds, multiply by 60
}

How to use this function:

calculateTimeDifference('01:14', '01:15')

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

When trying to access a string value for an ID, I encountered an error stating "Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)"

Currently, I am working on a project using React and Typescript. My goal is to retrieve a specific string with the key name id from an array of ten objects that contain the id. The screenshot displaying the code produces the desired output in the console; ...

Angular 6 - Accessing grandparent methods in grandchild components

I am in need of running the functions of the grandparent component: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.cs ...

Looking for an Angular Material component that displays a list of attributes?

I am trying to create a dynamic list of properties in Angular using Material Design that adjusts for different screen sizes. For example, something similar to this design: https://i.stack.imgur.com/EUsmV.png If the screen size decreases, the labels shou ...

Adding Rows Dynamically to Material Data Table in Angular 7

Is there a way to dynamically add data from a service into my table? I am receiving data from AuthenticationService dialog and attempted using this.dataSource.push(this.transaction);, but it did not work as expected. This is the code snippet where I trie ...

Choose historical dates with the dl-date-time-picker component within an Angular application

In my Angular 7 project, I have integrated a datetimepicker component called dl-date-time-picker. I want to prevent users from selecting previous dates in the date and time picker. Although I tried using the [selectFilter] attribute for this purpose, it en ...

Encountering difficulties importing an NPM library into StackBlitz

Hey there, I'm currently attempting to replicate an Angular example online but am encountering issues importing my Tabulator Library in stackblitz. I keep receiving an error when trying to import it in the hello component. import Tabulator from &apo ...

Issue with Loosing Focus in React TextInput when typing the letter "S"

My TextInput is acting strangely - it loses focus only when I type the letter s. All other letters work fine. <FormControl key={"1"} sx={{ m: 1 }} variant="outlined" onChange={handleFilterValueChange}> <InputLabel htmlFor=& ...

I am unable to process the information and transform it into a straightforward list

When using ngrx, I am able to retrieve two distinct data sets from storage. private getCatalog() { this.catalogStore.select(CatalogStoreSelectors.selectAllCatalogsLoadSuccess) .pipe( takeWhile(() => this.alive), take(1), ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Distilling the Essence of "Deity" in Handling Runtime Errors

Working with a client who has a unique "God" component for creating form fields can be quite challenging. The complexity arises from the fact that we are using material design for non-mobile platforms and Ionic for mobile platforms. This special component ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Ways to detect duplicate entries while submitting a form and sending an error message back to the front-end

I am currently working on a project that involves a Spring-boot back-end restful service serving an Angular client. The issue I am facing is related to submitting user-group data with unique codes from a form, but duplicates are being stored in the databas ...

Nested ControlGroup in Angular2's ControlArray

I've hit a roadblock trying to iterate through a ControlArray that has Controlgroups in a template. In TypeScript, I successfully created the ControlArray and added some ControlGroups by looping over data fetched from an API. The console displays the ...

Differences between ts-loader and babel-loader when working with TypeScript in webpack

Recently, I set out to compare the compiled output code between these two configurations. ts-loader { test: /\.tsx?$/, use: 'ts-loader', } babel-loader use: { loader: 'babel-loader', options: { p ...

Issues with page loading being halted by Angular2 child routes

Recently delving into Angular2, I am working on understanding routing, especially child routing. I have started my project based on the Angular2-seed project, focusing on setting up the routing structure. My routes are organized within functional modules ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

By default, the ng build command constructs the development environment rather than the production environment

Whenever I execute the "ng build" command in the terminal, it constructs the development environment instead of the production environment. If I use the "ng build --prod" command, everything works as expected. However, by default, it continues to build th ...

Tips for retrieving data sent through Nextjs Api routing

Here is the API file I have created : import type { NextApiRequest, NextApiResponse } from 'next/types' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() export default async function handler(req: NextApi ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Unable to establish a simulated environment and trial period for experimentation

I encountered the following errors during the test: TypeError: Cannot read properties of undefined (reading 'subscribe') Error: <toHaveBeenCalled> : Expected a spy, but got Function. I am having trouble understanding these errors. Here i ...