简体   繁体   中英

How can I display date and time in Angular template and keep it updated?

I need to display date and time in my angular template, and keep it updated, so when time is changed to show changed time ofcourse, application SHOULD look like this:

this is my .html template code:

<div class="top-right pull-right">
  <button type="button" class="btn xbutton-rectangle" (click)="logOut()">
    <div class="icon-user pull-left">
      <i class="fas fa-user fa-fw"></i>
      <span class="button-text">{{employee.FullName}}</span>
    </div>
    <div class="time-date pull-right">
      <p class="button-time">08:55</p>
      <p class="button-date">22.06.2018</p>
    </div>
  </button>
</div>

My .ts file:

@Component({
  selector: 'main-screen',
  templateUrl: './main-screen.component.html',
  styleUrls: ['./main-screen.component.css']
})
export class MainScreenComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
    //.. some methods 
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

  logOut() {
    this._globals.isAuthenticated = false;
    this._globals.loggedInUser = null;
    this._globals.token = null;
  }

} 

So how can I display date and time? and keep it updated when system date&time changes?

All you need to do is use the setInterval on your constructor

  date:Date; 
  constructor(){
    setInterval(() => {
      this.date = new Date()
    }, 1000)
  }

And use the date pipe to format the date and time

{{date   | date: "mm-dd-yyyy"}}
{{date   | date: "HH:mm:ss"}}

Demo

You should assign a variable to the date and update it every 0.1 second for example

public today = Date.now();

 setInterval(() => {
      this.today = Date.now();
    }, 100);

You can display it in your html like this if you want hours and minutes for example:

{{today | date:'HH:mm' }}

Look at https://angular.io/api/common/DatePipe for other Date format

Just add New function in your component like this

    @Component({
      selector: 'main-screen',
      templateUrl: './main-screen.component.html',
      styleUrls: ['./main-screen.component.css']
    })
    export class MainScreenComponent implements OnInit {

      constructor() {
      }

      ngOnInit() {
          this.utcTime();
      }

      ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
      }

       utcTime(): void {
        setInterval(function() {
            this.myDate = new Date();
            console.log(this.myDate); // just testing if it is working
        }, 1000);
    }

      logOut() {
        this._globals.isAuthenticated = false;
        this._globals.loggedInUser = null;
        this._globals.token = null;
      }

Then change your date format as you wish using angular Date pipe

The crazy easy was for me, is to do it directly in the HTML. Just add this to your HTML

<script>document.write(new Date().getFullYear());</script>

Because I love RxJS, I made a service using it, create a ClockService with this code:

import { Injectable } from '@angular/core';
import { interval, Observable, of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ClockService {

  constructor() { }

  getClock() : Observable<Date> {
    return interval(1000).pipe(
      mergeMap(() => of(new Date()))
    )
  }
}

And inject your service in your component.ts file like that:

export class AppComponent implements OnInit {

  clock: Observable<Date>;

  constructor(private clockService: ClockService) { }

  ngOnInit(): void {
    this.clock = this.clockService.getClock();
  }
  
}

Then finally, use it in your html like that, you can adjust the date filter as you want from the Angular DatePipe Documentation :

{{ clock | async | date:'HH:mm:ss'}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM