Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two dates in Days using angular

In my application I am getting message sent date from API response, I want to calculate the difference between current date and the date from API response in days(difference) using angular 8 and map in ngFor.

https://stackblitz.com/edit/angular-xv1twv?file=src%2Fapp%2Fapp.component.html

Please help me. Should I use moment.

like image 826
web developer Avatar asked Nov 19 '19 09:11

web developer


2 Answers

If this is all you need you can add plain code. For example:

calculateDiff(dateSent){
    let currentDate = new Date();
    dateSent = new Date(dateSent);

    return Math.floor((Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()) - Date.UTC(dateSent.getFullYear(), dateSent.getMonth(), dateSent.getDate()) ) /(1000 * 60 * 60 * 24));
}

You need to update your HTML to send the right date.

Example: https://stackblitz.com/edit/angular-bf5qer?file=src/app/app.component.ts

The code is adapted from https://www.w3resource.com/javascript-exercises/javascript-date-exercise-8.php and may require a few tests.

like image 64
saulotoledo Avatar answered Sep 19 '22 10:09

saulotoledo


You don't need to use momentjs.

  calculateDiff(data){
    let date = new Date(data.sent);
    let currentDate = new Date();

    let days = Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60 / 60 / 24);
    return days;
  }

<div *ngFor="let data of responseData" class="dataHolder">
  <div>{{data.title}}</div>
  <div>{{data.type}}</div>
  <div>{{data.msg}}</div>
   Message sent on: <div>{{data.sent}}</div>
   <div style="font-weight:bold;">sent {{calculateDiff(data)}}_ days ago</div>
</div>

like image 45
zmag Avatar answered Sep 19 '22 10:09

zmag