使用角度的 Days 中两个日期之间的差异

SRI*_*SRI 6 javascript date typescript angular angular8

在我的应用程序中,我从 API 响应中获取消息发送日期,我想使用 ngFor 中的 angular 8 和 map 计算当前日期与 API 响应日期之间的差异(天数(差异))。

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

请帮我。我应该使用时刻。

sau*_*edo 18

如果这就是你所需要的,你可以添加纯代码。例如:

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));
}
Run Code Online (Sandbox Code Playgroud)

您需要更新 HTML 以发送正确的日期。

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

该代码改编自https://www.w3resource.com/javascript-exercises/javascript-date-exercise-8.php,可能需要进行一些测试。


zma*_*mag 7

您不需要使用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;
  }
Run Code Online (Sandbox Code Playgroud)

<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>

Run Code Online (Sandbox Code Playgroud)