3

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?

billy_56
  • 649
  • 3
  • 11
  • 27

4 Answers4

13

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

Ivan Chaer
  • 6,980
  • 1
  • 38
  • 48
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
  • 1
    Isn't set interval bad for performances? and why in constructor? – billy_56 Jul 06 '18 at 12:41
  • depend on how you are using it. u need to know when to or not to cancel the interval using `clearInterval` otherwise memory gonna get overwhelmed – Sachila Ranawaka Jul 06 '18 at 12:43
  • https://stackoverflow.com/questions/2901108/how-do-i-clear-this-setinterval?answertab=active#tab-top – Sachila Ranawaka Jul 06 '18 at 12:47
  • I don't know.. maybe on component destroy or ? I don't know where is a good place and when to do it? – billy_56 Jul 06 '18 at 12:47
  • what If I rarely go to another component? so ngDestroy is called rarely, that it's dangerous to call clearnInterval rarely?? /for example I stay on same screen for 1-2 days/? :P – billy_56 Jul 06 '18 at 12:53
  • https://stackoverflow.com/questions/14034107/does-javascript-setinterval-method-cause-memory-leak – Artory Jul 06 '18 at 12:55
  • Should use Capital 'MM' for month, i was getting minute value instead of month.. {{date | date: "MM-dd-yyyy"}} – user1066231 Jul 22 '20 at 22:12
2

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

Artory
  • 845
  • 7
  • 13
1

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'}}
Mehdi Benmoha
  • 3,694
  • 3
  • 23
  • 43
  • is there a particular advantage to using `mergeMap(() => of(new Date()))` compared to just `map(x=>new Date())` seems unnecessary to map another `Observable`. Also `timer(0, 1000)` would return the first `Date()` immediately instead of 1 second later – MDK Apr 18 '22 at 20:56
0

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60