Menahem Gil
Menahem Gil

Reputation: 829

How to format timer in Angular

I want to format a timer in Angular, so bellow 10, 9 becomes 09, 8 - 08, etc. till 0 - 00.

I didn't find a built-in pipe. How can I achieve this? Thanks.

Upvotes: 1

Views: 905

Answers (4)

Mustahsan
Mustahsan

Reputation: 3862

You can use Angular Date Pipe like this:

<div>{{ today | date : 'EEEE, MMMM d, hh:mm:ss a' }}</div>

TS:

today: Date = new Date(2020,3,5,10,9,8);

Output:

Sunday, April 5, 10:09:08 AM

Working Demo

here hh, mm, ss will make sure you have two digits even when value is less than 10

Upvotes: 0

Manojkumar Muthukumar
Manojkumar Muthukumar

Reputation: 323

Use the following pipes as follows

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

{{datevar | date: 'short'}}

  • 'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
  • 'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
  • 'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
  • 'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
  • 'shortDate': equivalent to 'M/d/yy' (6/15/15).
  • 'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
  • 'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
  • 'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
  • 'shortTime': equivalent to 'h:mm a' (9:03 AM).
  • 'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
  • 'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
  • 'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Upvotes: 0

Sanjay Lohar
Sanjay Lohar

Reputation: 528

Here is a simple version, showing the time in seconds:

Component:

private timer;
private counter: Date;

ngOnInit() {
  this.timer = Observable.timer(0,1000)
    .subscribe(t => {
      this.counter = new Date(0,0,0,0,0,0);
      this.counter.setSeconds(t);
    });
}

ngOnDestroy(){
  this.timer.unsubscribe();
}

Template:

<div class="client-time">
  <span>Client time</span><br/>
  <strong>{{counter | date:'HH:mm:ss'}} seconds</strong>    
</div>

Upvotes: 0

Lajwat Kumar
Lajwat Kumar

Reputation: 304

import built-in function formatDate

import { formatDate } from '@angular/common';

12-Hours format

this.currentDateTime = formatDate(responseData.CreatedDateTime, 'MMM, dd yyyy hh:mm:ss aa', 'en-US');

24-Hours format

this.currentDateTime = formatDate(responseData.CreatedDateTime, 'MMM, dd yyyy HH:mm:ss', 'en-US');

Upvotes: 1

Related Questions