Find the length of time in Typescript (measured in hours, minutes, and seconds)

Trying to calculate the duration between two dates in TypeScript (Angular): 2021-11-19 21:59:59 and 2021-11-19 22:00:18

let startDate: Date = new Date(start);
  let endDate: Date = new Date(end);
  if(end != null) {
    let duration = new Date(endDate.getTime() - startDate.getTime());
    return duration.getHours() + ":" +  duration.getMinutes() + ":" + duration.getSeconds();
  } else {
    return "";
  }

However, the resulting time is incorrect: 1:0:19.

I am aiming for 00:00:19

EDIT

Tried the following but the result remains incorrect: 01:00:19

const datepipe: DatePipe = new DatePipe('en-US')
let formattedDate = datepipe.transform(duration, 'HH:mm:ss')

Answer №1

To retrieve the time value of a date, you can utilize the toLocaleTimeString() function which will specifically return the time based on the region. For more information, refer to the documentation.

To implement this in your code, simply modify the return statement as follows:

return duration.toLocaleTimeString([], {
   timeZone: 'UTC',
});

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

Why do callbacks in Typescript fail to compile when their arguments don't match?

In my current project, I encountered a scenario where a React callback led to a contrived example. interface A { a: string b: string } interface B { a: string b: string c: string } function foo(fn: (a: A) => void, a: A) { fn( ...

Exploring Custom Validator Comparisons in Angular

Having trouble comparing two input values in a custom validator. An error should occur if the minValue exceeds the maxValue. FormGroup: sumFormGroup = this.formBuilder.group({ from: ['', [Validators.min(0), sumValidator]], to: [&ap ...

Automatically divide the interface into essential components and additional features

Consider the following interfaces: interface ButtonProps { text: string; } interface DescriptiveButtonProps extends ButtonProps { visible: boolean, description: string; } Now, let's say we want to render a DescriptiveButton that utilize ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

Issue with Angular 2 Teamcity Error

Hey team, I'm encountering an error in TeamCity and could use some assistance. [05:40:13][Step 1/6] Update assembly versions: Scanning checkout directory for assembly information related files to update version to 12 [05:40:13][Step 1/6] scan: Search ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

Exploring the Benefits of Utilizing Cypress to Verify Form Fields and Manage Errors within Angular (version 13.3.0)

Recently started using Cypress with Angular version 13.3.0 and facing a validation issue with a form. Upon clicking a button, the form opens displaying various validation rules like 'First Name is required', 'Last Name', 'Gender&ap ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

What is the most efficient method for integrating third-party components just once in an Angular 8 application?

Is there a preferred method for configuring 3rd party components? I frequently use primeng p-table in various components throughout my application. I am looking to configure it globally for the entire application - enabling the paginator by default, setti ...

Importing custom pipes in Angular 2 becomes a bit tricky when working with data grouping

As a newcomer to Angular JS, I have recently started using Angular 2 for a project of mine. Here is an example of my JSON data: "locations": [ { "id": "ASS", "name": "test center", "city": "Staten Island", "zip": ...

Why is NestJs having trouble resolving dependencies?

Recently delving into NestJs, I followed the configuration instructions outlined in https://docs.nestjs.com/techniques/database, but I am struggling to identify the issue within my code. Error: Nest cannot resolve dependencies of the AdminRepository ...

Utilizing Lazy Loading Modules within an Angular 2 (v5) App

I'm struggling to implement lazy loading in my Angular 2 (version 5.1.3) project. While following Todd Motto's guide on Lazy Loading Code Splitting, I am hitting a roadblock in getting it to function correctly. My app consists of multiple modul ...

From HTML to Mat Table: Transforming tables for Angular

I am currently facing a challenge with my HTML table, as it is being populated row by row from local storage using a for loop. I am seeking assistance in converting this into an Angular Material table. Despite trying various suggestions and codes recommend ...

What is the reason behind TypeScript's lack of inference for function parameter types when they are passed to a typed function?

Check out the code snippets below: function functionA(x: string, y: number, z: SpecialType): void { } const functionWrapper: (x, y, z) => functionA(x, y, z); The parameters of functionWrapper are currently assigned the type any. Is there a way we can ...

Tips for creating a test to choose a movie from the MuiAutocomplete-root interface

I am currently utilizing Material UI with React using Typescript and I am looking to create a test for the autocomplete functionality using Cypress. Here is the approach I have taken: Identifying the Autocomplete component and opening it, Choosing an opti ...

Obtaining the Froala text editor's instance in React: A step-by-step guide

Is there a way to access the Froala editor instance within my React components? I've noticed that the official Froala documentation doesn't provide instructions for achieving this in React, only in jQuery. ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

Creating an endless scrolling feature with Ionic 3

My tech stack includes symfony3 and FosRestBundle for the backend, and Ionic 3 for the frontend development. While attempting to implement an InfiniteScroll feature following the Ionic documentation, I encountered an issue where only the loading text and ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

What is the code to continuously click on the "Next" button in playwright (typescript) until it is no longer visible?

Currently, I have implemented a code that clicks the next button repeatedly until it no longer appears on the pagination. Once the last page is reached, I need to validate the record. The problem arises when the script continues to search for the locator ...