How I can create Angular custom Date Pipe
You can create class for property like wise I have use environment class for date format DATE_FORMAT and assign by default dd-MM-yyyy format and use in date pipe. By this approach only change the value of DATE_FORMAT and we can easily change the format of date else where.
import { Pipe, PipeTransform } from '@angular/core';
import { environment } from "../../../../environments/environment";
import { DatePipe } from "@angular/common";
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
if(Object.keys(environment).indexOf("DATE_FORMAT") >= 0){
return super.transform(value, environment.DATE_FORMAT);
}
return super.transform(value, 'dd-MM-yyyy');
}
html
<span>{{ data.date | dateFormat }}</span>
Adding to the nice answer given by Sachila above, you can also implement the full functionality in your custom pipe itself.
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
// adding a default format in case you don't want to pass the format
// then 'yyyy-MM-dd' will be used
transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
date = new Date(date); // if orginal type was a string
date.setDate(date.getDate()-day);
return new DatePipe('en-US').transform(date, format);
}
}
And use your custom Pipe like:
<span>{{data.nextCertificateUpdate | mypipe: 28: 'yyyy-MM-dd'}}</span>
See a working example here: https://stackblitz.com/edit/angular-995mgb?file=src%2Fapp%2Fapp.component.html