How can I display date and time in Angular template and keep it updated?
11,471
Solution 1
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"}}
Solution 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
Author by
billy_56
Updated on June 14, 2022Comments
-
billy_56 almost 2 years
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?