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

2

51

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.

Tacitus answered 22/12, 2016 at 9:47 Comment(1)
@Community, what I want ask is how to use angular2 date pipe in services and directives not only in component which is different with question #36817048 now, so please help to correct your tag.Tacitus
B
104

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());
}
Bosch answered 22/12, 2016 at 12:4 Comment(3)
Thanks very much @Alexander, it works for me, but I need to import DatePipe like thisimport { DatePipe } from '@angular/common/src/pipes'; otherwise webstorm will show an error.Tacitus
@LarryChen, this just means that there's something else wrong with your setup, mine does understand it. May be you're using old version of ng2 or WebStorm.Bosch
my version:"@angular/common": "^2.3.0", webstorm: 2016.3.2Tacitus
F
35

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.

Fenestration answered 22/12, 2016 at 9:54 Comment(6)
Thanks Avnesh, I found the constructor of DatePipe is constructor(_locale: string), your suggestion missed a parameter, but anyway it inspired me a lot.Tacitus
Sample Code combining both answers new DatePipe('en-US').transform(myDate, 'yyyy-dd-MM');Trinette
Please edit to add locale as @Trinette has shownContumely
@Avnesh Shakya Lcan you tell me how to add "America/Los_Angeles" time in above function?Metz
@KapilSoni see this if it helps: #67732283Fenestration
@AvneshShakya sir i have tried code but its give ne different time const text = new Date(this.salesOrderModel.PostingDate).toLocaleString('en-US', { timeZone:'America/Los_Angeles'});Metz

© 2022 - 2024 — McMap. All rights reserved.