首页 > 解决方案 > 使用角度的天数中的两个日期之间的差异

问题描述

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

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

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

标签: javascriptangulartypescriptdateangular8

解决方案


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

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

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

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

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


推荐阅读