angularcurrent-time

How to show current time in angular without using setInterval()


I want to show current active time in angular 11.

I did like this

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

But I do not need timer.

Is there any other way to show current time?


Solution

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

    Working Demo