Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  194] [ 3]  / answers: 1 / hits: 26301  / 6 Years ago, tue, october 2, 2018, 12:00:00

I'm working on angular 5 I want to create a custom date pipe that allows me to subtract some days from a date :


This how I display my date value :


 <span>{{data.nextCertificateUpdate | date:'yyyy-MM-dd'}}</span>  

for example this display a value like : 2018-08-29


I ask if it's possible to create a pipe that allow me to substract a number of days for example 28 from this date ?


Something like :


<span>{{data.nextCertificateUpdate | mypipe:28 }}</span>  

and this should display value like : 2018-08-01


Thanks for any help


More From » angular

 Answers
10

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


[#53394] Thursday, September 27, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alessandrol

Total Points: 286
Total Questions: 107
Total Answers: 109

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
;