I want to use angular2's date pipe in services and directives script files(not only in HTML).
Does anyone have any ideas?
Can't upload code cos some policy restrictions, sorry about that.
I want to use angular2's date pipe in services and directives script files(not only in HTML).
Does anyone have any ideas?
Can't upload code cos some policy restrictions, sorry about that.
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());
}
import { DatePipe } from '@angular/common/src/pipes';
otherwise webstorm will show an error. –
Tacitus "@angular/common": "^2.3.0"
, webstorm: 2016.3.2 –
Tacitus 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.
constructor(_locale: string)
, your suggestion missed a parameter, but anyway it inspired me a lot. –
Tacitus new DatePipe('en-US').transform(myDate, 'yyyy-dd-MM');
–
Trinette © 2022 - 2024 — McMap. All rights reserved.