Home > Enterprise >  Calculate difference between date times in typescript angular
Calculate difference between date times in typescript angular

Time:03-15

I have my two string values startTime that is written in format: 14/03/2022, 17:12:19 and stopTime that is written in format: 14/03/2022, 17:15:19 and I need to get difference between these two times in angular typescript file I need to get 03:00 as my answer.

This is what I tried but getTime() method seem to not exist 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 tried parsing with:

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

But this only prints Nan

This is my html file:

<div >
    <h1 >Timely Application</h1>
</div>
<div>
    <app-table-form></app-table-form>
</div>
<body style="text-align: center;">
<div>
    <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  (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>

Any suggestions?

CodePudding user response:

You can try something like this:

this.getDifference(this.startTime, this.stopTime); // use your vars' names


  getDifference(start: string, stop: string) {
    // getting startTime timestamp:
    let startTimestamp = this.getTimestamp(start);
    // getting stopTime timestamp:
    let stopTimestamp = this.getTimestamp(stop);
    // getting the difference in various formats:
    // hh:mm:ss
    let differenceInSecs = stopTimestamp - startTimestamp;
    let inHhMmSsFormat = new Date(differenceInSecs * 1000)
      .toISOString()
      .slice(11, 19);
    console.log('Difference in hh:mm:ss format: ', inHhMmSsFormat);
    // mm:ss
    let inMmSsFormat = new Date(differenceInSecs * 1000)
      .toISOString()
      .slice(14, 19);
    console.log('Difference in mm:ss format: ', inMmSsFormat);
  }

  getTimestamp(time: string) {
    let timeFirst = time.split(', ')[0].split('/');
    let timeY = timeFirst[2];
    let timeM = timeFirst[1];
    let timeD = timeFirst[0];
    let timeSecond = time.split(', ')[1];
    let timestamp =
      new Date(
        Date.parse(
          timeY   '-'   timeM   '-'   timeD   ' '   timeSecond   ' 0000'
        )
      ).getTime() / 1000;
    return timestamp;
  }

Stackblitz: https://stackblitz.com/edit/angular-wk2fet

CodePudding user response:

this.myStartDate = new Date(startTime);

Using the above line to create a Date can’t work, because it requires a number as an argument, not a string.

But if that's the only string format you can use, here I’ve prepared a short solution for you:

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