0

我想以 11 角显示当前的活动时间。

我确实喜欢这个

   setInterval(() => {
      this.UKTime = formatDate(
        Date.now(),
        "dd-MM-yy hh:mm a",
        "en-US",
        "+0100"
      );
      this.SLTime = formatDate(
        Date.now(),
        "dd-MM-yy hh:mm a",
        "en-US",
        "+0530"
      );
    }, 1000);

但我不需要计时器。

有没有其他方法可以显示当前时间?

4

1 回答 1

1

app.component.ts

export class AppComponent implements OnInit, OnDestroy {
  rxTime = new Date();
  intervalId;
  subscription: Subscription;

  ngOnInit() {

    // Using RxJS Timer
    this.subscription = timer(0, 1000)
      .pipe(
        map(() => new Date()),
        share()
      )
      .subscribe(time => {
        let hour = this.rxTime.getHours();
        let minuts = this.rxTime.getMinutes();
        let seconds = this.rxTime.getSeconds();
        //let a = time.toLocaleString('en-US', { hour: 'numeric', hour12: true });
        let NewTime = hour + ":" + minuts + ":" + seconds
        console.log(NewTime);
        this.rxTime = time;
      });
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

app.component.html

RxJS Clock:
<div>{{ rxTime | date: 'hh:mm:ss a' }}</div>

工作演示

于 2021-08-05T06:40:03.560 回答