Determine the time interval between two dates in an Angular TypeScript project

My challenge involves handling two string values: startTime, which is formatted as 14/03/2022, 17:12:19, and stopTime, which is in the format of 14/03/2022, 17:15:19. The goal is to calculate the difference between these times within an Angular TypeScript file, resulting in an answer of 03:00.

Initially, I attempted using the getTime() method, but it appears not to be available in TypeScript:

  calculateDuration(startTime:string,stopTime:string)
  {
    this.myStartDate = new Date(startTime);
    this.myEndDate = new Date(stopTime);
    this.diff = this.myEndDate.getTime() - this.myStartDate.getTime();
    console.log(this.diff);
  }

I also experimented with parsing like this:

  calculateDuration(startTime:string,stopTime:string)
  {
    this.myStartDate = Date.parse(startTime)
    this.myEndDate = Date.parse(stopTime);
    this.diff = this.myEndDate - this.myStartDate;
    console.log(this.diff);
  }

However, this approach only yields a result of Nan.

In addition, here is my HTML code snippet:

<div class="jumbotron">
    <h1 class="display-4 text-center">Timely Application</h1>
</div>
<div>
    <app-table-form></app-table-form>
</div>
<body style="text-align: center;">
<div>
    <table class="table" style="margin:1em auto;" >
        <thead>
            <tr>
                <th>Project Name</th>
                <th>Start Time</th>
                <th>Stop Time</th>
                <th>Duration</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let tf of service.listofTime">
                <td (click)="changeForm(tf)">{{tf.projectName}}</td>
                <td (click)="changeForm(tf)">{{tf.startTime}}</td>
                <td (click)="changeForm(tf)">{{tf.stopTime}}</td>
                <td (click)="changeForm(tf)">{{tf.duration}}</td>
                <td>
                    <i class="far fa-trash-alt fa-lg text danger" (click)="(onDelete(tf.timeId))"></i>
                    <button style="margin-left: 40px;" (click)="(calculateDuration(tf.startTime,tf.stopTime))">Calculate duration</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>
</body>

Open to any suggestions or solutions!

Answer №1

If you're looking to calculate the time difference between two points, consider implementing a function like the one below:

this.calculateTimeDifference(this.startTime, this.stopTime); // utilize your own variables


  calculateTimeDifference(start: string, stop: string) {
    // obtaining start timestamp:
    let startTimestamp = this.getTimestamp(start);
    // obtaining stop timestamp:
    let stopTimestamp = this.getTimestamp(stop);
    // calculating the time difference in different formats:
    // hh:mm:ss
    let differenceInSeconds = stopTimestamp - startTimestamp;
    let formattedHhMmSs = new Date(differenceInSeconds * 1000)
      .toISOString()
      .slice(11, 19);
    console.log('Time difference in hh:mm:ss format: ', formattedHhMmSs);
    // mm:ss
    let formattedMmSs = new Date(differenceInSeconds * 1000)
      .toISOString()
      .slice(14, 19);
    console.log('Time difference in mm:ss format: ', formattedMmSs);
  }

  getTimestamp(time: string) {
    let firstPart = time.split(', ')[0].split('/');
    let yyyy = firstPart[2];
    let mm = firstPart[1];
    let dd = firstPart[0];
    let secondPart = time.split(', ')[1];
    let timestamp =
      new Date(
        Date.parse(
          yyyy + '-' + mm + '-' + dd + ' ' + secondPart + '+0000'
        )
      ).getTime() / 1000;
    return timestamp;
  }

Check it out on Stackblitz: https://stackblitz.com/edit/angular-wk2fet

Answer №2

this.myStartDate = new Date(startTime);

Attempting to initialize a Date object with a string like this will not work, as it requires a numerical argument instead of a string.

If you are limited to using this specific string format, here is a concise solution for handling it:

const startDate: string = '14/03/2022, 17:12:19';
const endDate: string = '14/03/2022, 17:15:19';

const calculateDuration = (startTime:string, stopTime:string) => {

 const lPartSplittedStartDate: string[] = startTime.split('/');
 const rPartStartDate: string[] = lPartSplittedStartDate[2].split(',');
 const rPartSplittedStartDate: string[] = rPartStartDate[1].split(':');

 const myStartDate: Date = new Date(
    parseInt(lPartSplittedStartDate[2]),
    parseInt(lPartSplittedStartDate[1]),
    parseInt(lPartSplittedStartDate[0]),
    parseInt(rPartSplittedStartDate[0]),
    parseInt(rPartSplittedStartDate[1]), 
    parseInt(rPartSplittedStartDate[2])
 );

 const startTimestamp: number = myStartDate.getTime();

 const lPartSplittedEndDate: string[] = stopTime.split('/');
 const rPartEndDate: string[] = lPartSplittedEndDate[2].split(',');
 const rPartSplittedEndDate: string[] = rPartEndDate[1].split(':');

 const myEndDate: Date = new Date(
    parseInt(lPartSplittedEndDate[2]),
    parseInt(lPartSplittedEndDate[1]),
    parseInt(lPartSplittedEndDate[0]),
    parseInt(rPartSplittedEndDate[0]),
    parseInt(rPartSplittedEndDate[1]), 
    parseInt(rPartSplittedEndDate[2])
 );

 const endTimestamp: number = myEndDate.getTime();

 const newNumber: number = endTimestamp - startTimestamp;
 const diffMinutes: number = Math.ceil(newNumber / (1000 * 60));

 console.log(diffMinutes)

 return diffMinutes;
}

calculateDuration(startDate, endDate);

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

Incorrectly identifying the week number when utilizing DATEPART in SQL Server

Help! I am facing an issue where select datepart(ww, '20100208') is showing week 7 in SQL Server 2000. However, based on the ISO 8601 specification, 08.02.2010 should actually be week 6. This discrepancy is causing errors in my delivery week ca ...

Deploy the dist folder generated by ng build with the help of msdeploy

Has anyone successfully used msdeploy to install the output of ng build --prod (the dist folder) into IIS? I attempted to do so with this command: msdeploy.exe -verb:sync -source:package=c:\Workspace\MyProject\dist.zip -dest:auto -setPara ...

How can elements be displayed differently depending on the return value of a function?

Basically, I am looking to display different content based on the status of a job: Show 'Something1' when the job is not processing Show 'Something2' when the job is running and has a status of '0' Show 'Something3&apos ...

"Error: The specified object does not have the capability to support the property or method 'includes'." -[object Error]

Recently, I developed a method that utilizes both indexOf() and includes(). However, I encountered an error message stating "Object doesn't support property or method 'includes'". I have attempted to run the method on both Internet Explorer ...

Please provide a declaration or statement when using the subscribe() method in TypeScript 3.0.1

I'm encountering a "declaration or statement expected" error after updating TypeScript and Angular. getTopics() { this._dataService.getTopics().subscribe(res => { this.topics = res; for (let i = 0; i < this.topics.length; i ...

Retrieve information from Wordpress API and integrate it into Angular 7

I'm having an issue with pulling post data from Wordpress into my Angular 7 app. Even though I can see the data in the console, I'm unable to display it in my component. Any tips on how to resolve this? app.component.ts import { Component, OnIn ...

Use Jest to mimic express.Router()

When working with my code under test, I need to mock the router: import * as express from "express"; const router = express.Router(); // This is the part I want to mock router.route(...).post(...); router.route(...).get(...); Here's what I tried ...

"Font Awesome icons are only visible online on the -dev website, not visible anywhere

I followed the recommended steps on Fontawesome's official site to install the fontawesome library. I used the following command: npm install --save-dev @fortawesome/fontawesome-free For production purposes, I included the following code in my index ...

How can we modify array.map to return a unique type signature?

Take a look at these two straightforward functions written in typescript: function generate(): Array<[number, number]> { return [[0, 1], [2, 3]]; } function mutate(input: Array<[number, number]>): Array<[number, number]> { return in ...

What is the process for creating a personalized tag?

Having created a component similar to the one below. In MyButton.tsx import React from 'react'; import { Button } from '@material-ui/core'; import { Theme, makeStyles, createStyles } from "@material-ui/core/styles"; interface IMyButt ...

Upgrading to Angular 10 Ivy and Webpack 4 - Say Goodbye to ng Debug Info

After successfully setting up an Angular 10 Ivy project using @ngtools/webpack, everything has been running smoothly. However, the problem arises in production builds where debug functions such as ng.getContext(), ng.getHostElement(), and $0.__ngContext__ ...

How can you specify the active route in Angular?

I am curious about whether it is possible to set the active route from a script instead of just from the HTML template. Let me provide an example: @Component({ template: `<input type="button" (click)="back()" value="back" ...

TypeORM's OneToMany relationship creates a corresponding column in the database

I am working with three tables and entities: client store store_client The relationships between these entities are as follows: Client: @OneToMany((type) => StoreClient, (storeClient) => storeClient.client, { eager: false }) storeClient: StoreClie ...

Tips for utilizing Angular 9 to automatically scroll to the end of an element's content

My website features a large form with a submission button. Below this button, I have included a div containing an image of a progress bar to indicate to the user that their http request is being processed: <div *ngIf="formSubmitted"> &l ...

Extracting data enclosed in double quotes from a JSON list retrieved through a curl request

I have been trying to access an online JSON file and download it, however, I am encountering difficulties in parsing the data. Specifically, I am looking to extract IP addresses that are enclosed within double quotes from the JSON file. While I can use jq ...

Having trouble iterating over an array of objects in Typescript within an Angular application?

When working on my project, I encountered a challenge with fetching data from an API that provides trip entities. Here is the model structure I am using: //Trip.model.ts export class Trip{ created_at?:Date; updated_at?:Date; .... bunch of fields } ...

Maintaining consistency between two fields? Foo<X> (x:X leads to y:Y)

Is there a way to establish a relationship between two types in Typescript? For instance, I need to ensure that the TypeContent in the example below is appropriate for the type T. export type DataReport<T extends Type, TypeContent> = { id: number ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Encountering the error message "TypeError: Unable to access properties of null (reading 'get')" while utilizing useSearchParams within a Storybook file

Looking at the Next.js code in my component, I have the following: import { useSearchParams } from 'next/navigation'; const searchParams = useSearchParams(); const currentPage = parseInt(searchParams.get('page') || '', 10) || ...

There was an issue encountered when executing Angular in Cypress: The module '@angular/compiler' is not found

While conducting Cypress E2E testing, Angular appears to not be running properly. We encountered the following Angular error after migrating to version 18: The error is originating from your test code, not Cypress. > The injectable 'PlatformNaviga ...