Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use angular2 built-in date pipe in services and directives script files [duplicate]

I need to use angular2's date pipe in services and directives script files(not only in HTML).

Does anyone have ideas?

Can't upload code cos some policy restrictions, sorry about that.

like image 911
Chen Dachao Avatar asked Dec 22 '16 09:12

Chen Dachao


People also ask

How do I use DatePipe in HTML?

“how to use date pipe in angular html” Code Answer'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).

What is date pipe in angular?

Angular Date Pipe allows us to format dates in Angular using the requested format, time zone & local information. It comes with built-in pre-defined formats. We can also customize the date format by creating custom format strings. We can set the time zone, country locale, etc.


2 Answers

Since CommonModule does not export it as a provider you'll have to do it yourself. This is not very complicated.

1) Import DatePipe:

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

2) Include DatePipe in your module's providers:

NgModule({   providers: [DatePipe] }) export class AppModule { } 

or component's providers:

@Component({   selector: 'home',   styleUrls: ['./home.component.css'],   templateUrl: './home.component.html',   providers: [DatePipe] }) export class HomeComponent { ... 

3) Inject it into your component's constructor like any other service:

constructor(private datePipe: DatePipe) { } 

4) Use it:

ngOnInit() {     this.time = this.datePipe.transform(new Date()); } 
like image 66
Alexander Leonov Avatar answered Oct 20 '22 05:10

Alexander Leonov


In your component

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

If you are using Angular 2, 4 version, try

new DatePipe().transform(myDate, 'yyyy-dd-MM'); 

If you are using Angular 6 and above

new DatePipe('en-US').transform(myDate, 'yyyy-dd-MM'); 

Hope this will help.

like image 45
Avnesh Shakya Avatar answered Oct 20 '22 04:10

Avnesh Shakya