如何在打字稿中获得给定时间和当前时间的差异是

How to get difference in given time and current time in typescript is

我正在使用 angular 7,如果满足以下条件,我想显示组件 html 中的元素:给定时间早于当前时间。

我尝试了以下逻辑

 getTimeDiff(time, date)
    {

         const dateNow = new Date()
         const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

         const diff = Math.abs(Math.abs(dateNow.getTime() - slotDate.getTime()) /  3600000)

        //if diff is not negative
       if(diff) {
         return false
      } 
        else {
         return true
       }
     }

HTML

<span *ngIf="getTimeDiff(result.endtime, result.date)"> open </span>

更新

使用 *ngFor 显示元素,所以我无法在 ngOnInit() 中调用 getTimeDiff。

<div *ngFor="let result of results">
    <span *ngIf="getTimeDiff(result.endtime, result.date)"> open </span>
</div>

但出于某种原因我得到:

ViewAppointmentsComponent.html:30 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: 6.0732225'. Current value: 'null: 6.0732252777777775'.

Angular 运行更改检测,当它发现传递给子组件的某些值已更改时 Angular 抛出错误 ExpressionChangedAfterItHasBeenCheckedError.

最好创建一个变量来保存信息,而不是在每次更改检测时调用相同的函数

different = false;  //<-- hold the difference state.

getTimeDiff(time, date)
{

     const dateNow = new Date()
     const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(dateNow.getTime() - slotDate.getTime()) /  3600000)

    //if diff is not negative
   if(diff) {
     this.different = false  //<-- change to false.
  } 
    else {
     this.different  = true  //<-- change to true.
   }
 }

html

<span *ngIf="different"> open </span>

Note : Do not forget to call getTimeDiff function in appropriate place like ngOnInit if you want to get one time .

这是一个生命周期错误,说 Angular 已经检查了一个值,但您出于某种原因正在更新它。

如果您在函数中放置控制台日志,您会看到它被调用了 很多 时间。

这是因为绑定到指令的函数在每次用户交互时都会被调用。

这意味着每次调用它时,它都会获得一个新的日期值(+1 毫秒)

为避免这种情况,请在创建组件时创建日期并对其进行比较。如果你愿意,你可以在某个时候更新它,但不是在函数本身。

constructor(private now = new Date()) {}

getTimeDiff(time, date)
{
     const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(this.now.getTime() - slotDate.getTime()) /  3600000)

    //if diff is not negative
   if(diff) {
     return false
  } 
    else {
     return true
   }
 }

编辑

为避免函数被调用,您可以使用一个随变化而更新的变量:

this.timeDiff: boolean;

ngDoCheck() {
  this.timeDiff(this.result.endtime, this.result.date);
}

getTimeDiff(time, date)
{
     const slotDate = new Date(`${date} ${time}`);  // say time = '10:30:00' and date = '2018-11-14' 

     const diff = Math.abs(Math.abs(this.now.getTime() - slotDate.getTime()) /  3600000)

    //if diff is not negative
   if(diff) {
     this.timeDiff = false;
  } 
    else {
     this.timeDiff =  true;
   }
 }

在你的HTML

<span *ngIf="timeDiff"> open </span>

ngDoCheck 是一个生命周期钩子(类似 ngOnInit),可以总结为

Function that detect changes that are not tracked by Angular