4

I have static timestamp from backend and I want to refresh the pipe every 1 second to get date from now and this my pipe

    import { Pipe, PipeTransform } from '@angular/core';
import moment from 'moment';
@Pipe({
  name: 'dateFormat'
})
export class DateFormatPipe implements PipeTransform {

  transform(date: string): string {

    return moment.utc(date, 'X').local().format('DD-MM-YYYY h:mm:ss a');
  }

}

in this case it just convert time stamp to this format , I want to keep date updated how can I do this ?

2 Answers2

6

You should return an observable and use asyncPipe as well.

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
import { interval, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Pipe({
  name: 'dateFormat'
})
export class DateFormatPipe implements PipeTransform {

  transform(date: string): Observable<string> {
    return interval(1000).pipe(map(() => { return moment().format('DD-MM-YYYY h:mm:ss a') }));
  }

}

And you should use it like: {{ 'param' | dateFormat | async}}

msleiman
  • 146
  • 5
  • Use `timer(0, 1000)` instead of `interval(1000)` if you want the pipe to return immediately! https://stackoverflow.com/a/44166071/2966288 – AvahW Jul 23 '23 at 20:34
0

I think you just have to refresh your time that is passed into the pipe every second?

Like

currentTime$ = Observable.interval(1000).pipe(map(() => { return new Date() } ))
Peter Bucher
  • 48
  • 1
  • 5