如何以分钟为单位计算和显示时差Angular2

时间:2019-03-13 22:42:16

标签: javascript angular typescript datetime time

我有一个角度应用程序,它使用*ngFor显示订单,每个订单都有一个datetime字段以及创建日期。我想创建一个计时器,以分钟为单位显示客户等待其订单的时间,计算order.time与现在之间的差异。我尝试使用amDifference管道,但是由于某种原因,它对所有记录都显示了相同的输出。对于一项而言,这样做很容易,但是我不知道如何在*ngFor循环中进行。

<mat-card class="order-card" *ngFor="let order of orders?.orders">
  <mat-card-subtitle>
    Customer Name: {{ order.customerName }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Table Number: {{ order.tableNumber }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Food: {{ order.food }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Drink: {{ order.drink }}
  </mat-card-subtitle>

  <mat-card-subtitle>
    Estimated Wait Time: {{ order.waitTime }} minutes
  </mat-card-subtitle>

  <mat-card-subtitle>
    Actual wait time: <!-- this is where I want to display dynamic time diffrence between now and order.time -->
  </mat-card-subtitle>
  <button mat-button class="delete-button" color="primary" (click)="deleteOrder(order.orderId)">Remove Order</button>
</mat-card>

2 个答案:

答案 0 :(得分:1)

我使用的方法不同于使用amDifference /自定义管道。查看我的代码并提出建议/分享反馈。我正在预先计算课堂上的分钟差异。

order.ts

export class Order {
mins:number;
    constructor(private id:number, private time:Date, private now:Date) {
        let diffInMilliSecs:number  = (this.now.getTime()-time.getTime()) ;

        let diffinMins: number = diffInMilliSecs / 1000/60;
        this.mins =Math.round(diffinMins);
    }
}

app.component.ts

import { Component} from '@angular/core';
import { Order } from './order';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent{
  title = 'Orders';
  dateNow=new Date();



  orders = [ new Order(1,new Date("13 Mar 2019 19:50:14 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:15:20 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:45:55 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:15:02 EDT"),this.dateNow),
  new Order(1,new Date("13 Mar 2019 20:15:00 EDT"),this.dateNow)];

}

app.component.html

<h1>  {{title}} </h1>
<h3> Time Now: {{dateNow}}</h3>

<table>
  <tr><th> Order#</th> <th>Order time</th> <th>Wait time (in mins)</th></tr>
  <tr *ngFor="let order of orders">
    <td>{{order.id}}</td>
    <td>{{order.time | date:'medium'}}</td>
     <td>{{order.mins}}</td> 
  </tr>

</table>

Output

答案 1 :(得分:0)

您可以尝试

{{ new Date() | amDifference:  order.time : 'minutes'}} minutes