Angular - Use pipes in services and components
This answer is now outdated
recommend using DI approach from other answers instead of this approach
Original answer:
You should be able to use the class directly
new DatePipe().transform(myDate, 'yyyy-MM-dd');
For instance
var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');
As usual in Angular, you can rely on dependency injection:
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
Add DatePipe
to your providers list in your module; if you forget to do this you'll get an error no provider for DatePipe
:
providers: [DatePipe,...]
Update Angular 6: Angular 6 now offers pretty much every formatting functions used by the pipes publicly. For example, you can now use the formatDate
function directly.
import { formatDate } from '@angular/common';
class MyService {
constructor(@Inject(LOCALE_ID) private locale: string) {}
transformDate(date) {
return formatDate(date, 'yyyy-MM-dd', this.locale);
}
}
Before Angular 5: Be warned though that the DatePipe
was relying on the Intl API until version 5, which is not supported by all browsers (check the compatibility table).
If you're using older Angular versions, you should add the Intl
polyfill to your project to avoid any problem.
See this related question for a more detailed answer.