回答:
Angularではいつものように、依存関係の注入に依存することができます:
import { DatePipe } from '@angular/common';
class MyService {
  constructor(private datePipe: DatePipe) {}
  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}DatePipeモジュールのプロバイダーリストに追加します。これを忘れると、エラーが発生しますno provider for DatePipe。
providers: [DatePipe,...]Angular 6の更新:Angular 6は、パイプが公に使用するほぼすべてのフォーマット関数を提供するようになりました。たとえば、formatDate関数を直接使用できるようになりました。
import { formatDate } from '@angular/common';
class MyService {
  constructor(@Inject(LOCALE_ID) private locale: string) {}
  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}Angular 5より前:ただし、DatePipeバージョン5まではIntl APIに依存していたため、すべてのブラウザーでサポートされているわけではありません(互換性の表を確認してください)。
古いAngularバージョンを使用している場合はIntl、プロジェクトにポリフィルを追加して問題を回避する必要があります。より詳細な回答については、この関連質問を参照してください。
このアプローチの代わりに他の回答からDIアプローチを使用することをお勧めします
クラスを直接使用できるはずです
new DatePipe().transform(myDate, 'yyyy-MM-dd');例えば
var raw = new Date(2015, 1, 12);
var formatted = new DatePipe().transform(raw, 'yyyy-MM-dd');
expect(formatted).toEqual('2015-02-12');Dateコンストラクターを使用する場合、月は基準0になります。だから、01月で、12月です。行方不明の修正y
                    error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'string'.  れない....   オンラインvar formatted = new DatePipe().transform(raw, ['yyyy-MM-dd']);
                    @NgModule({ providers:[DatePipe] })、次にクラスでインポートして注入します  constructor( private datePipe: DatePipe ){}
                    はい、シンプルなカスタムパイプを使用することで可能です。カスタムパイプを使用する利点は、将来的に日付形式を更新する必要がある場合に、単一のファイルを更新できることです。
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'MMM-dd-yyyy');
        return value;
    }
}
{{currentDate | dateFormatPipe }}
このパイプはいつでもどこでも使用できます。コンポーネント、サービスなど
例えば
export class AppComponent {
  currentDate : any;
  newDate : any;
  constructor(){
    this.currentDate = new Date().getTime();
    let dateFormatPipeFilter = new dateFormatPipe();
    this.newDate = dateFormatPipeFilter.transform(this.currentDate);
    console.log(this.newDate);
}
依存関係をインポートすることを忘れないでください。
import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'
DatePipeはプロバイダーではないため、注入できないため、エラーが発生しました。1つの解決策は、それをプロバイダーとしてアプリモジュールに配置することですが、私の好ましい解決策は、それをインスタンス化することでした。
DatePipeのソースコードを調べて、ロケールがどのように取得されるかを確認しました:https : //github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174
私はそれをパイプ内で使用したかったので、私の例は別のパイプ内にあります:
import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
    name: 'when',
})
export class WhenPipe implements PipeTransform {
    static today = new Date((new Date).toDateString().split(' ').slice(1).join(' '));
    datePipe: DatePipe;
    constructor(@Inject(LOCALE_ID) private locale: string) {
        this.datePipe = new DatePipe(locale);
    }
    transform(value: string | Date): string {
        if (typeof(value) === 'string')
            value = new Date(value);
        return this.datePipe.transform(value, value < WhenPipe.today ? 'MMM d': 'shortTime')
    }
}
ここで重要なのは、AngleのコアからInjectとLOCALE_IDをインポートし、それを注入して、DatePipeに渡して適切にインスタンス化できるようにすることです。
アプリモジュールで、次のようにプロバイダー配列にDatePipeを追加することもできます。
import { DatePipe } from '@angular/common';
@NgModule({
    providers: [
        DatePipe
    ]
})
これで、必要に応じてコンストラクターに注入することができます(cexbrayatの回答のように)。
どちらの解決策も機能しましたが、どのAngularが最も「正しい」と見なすかはわかりませんが、Angleはプロバイダー自体として日付パイプを提供していなかったため、手動でインスタンス化することを選択しました。
newます。パイプを上回ったときに、ロケールをDIする必要があるからです。@Inject(LOCALE_ID) private locale: string構文全体が面倒です。
                    依存関係をパイプに注入するために 'new myPipe()'を実行したくない場合は、プロバイダーなどのコンポーネントを注入し、newなしで使用できます。
例:
// In your component...
import { Component, OnInit } from '@angular/core';
import { myPipe} from './pipes';
@Component({
  selector: 'my-component',
  template: '{{ data }}',
  providers: [ myPipe ]
})
export class MyComponent() implements OnInit {
  data = 'some data';
  constructor(private myPipe: myPipe) {}
  ngOnInit() {
    this.data = this.myPipe.transform(this.data);
  }
}
コンポーネントでカスタムパイプを使用する場合は、追加できます
@Injectable({
  providedIn: 'root'
})
カスタムパイプへの注釈。その後、サービスとして使用できます
providedIn: 'root'私たちのパイプの中に持っているのがいいですか、それともパイプが使用されているローカルモジュールで提供されているのですか?
                    Angular 6 formatDate以降、@angular/commonユーティリティからインポートしてコンポーネント内で使用できます。
https://github.com/smdunn/angular/commit/3adeb0d96344c15201f7f1a0fae7e533a408e4aeに侵入された
私は次のように使用できます:
import {formatDate} from '@angular/common';
formatDate(new Date(), 'd MMM yy HH:mm', 'en');
ロケールを指定する必要がありますが
formatDate()を使用して、サービスまたはコンポーネントtsの日付をフォーマットできます。構文:-
formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string
このような一般的なモジュールからformatDate()をインポートし、
import { formatDate } from '@angular/common';
このようなクラスで使用するだけで、
formatDate(new Date(), 'MMMM dd yyyy', 'en');
このようにangularによって提供される事前定義されたフォーマットオプションを使用することもできます、
formatDate(new Date(), 'shortDate', 'en');
他のすべての定義済みフォーマットオプションはここで確認できます。