在AngularJS中,我能够在服务和控制器中使用过滤器(管道),使用类似于下面的语法:

$filter('date')(myDate, 'yyyy-MM-dd');

在Angular中,可以在服务/组件中像这样使用管道吗?


当前回答

我使用这个方法:

 import { Component, OnInit } from '@angular/core';
    import {DatePipe} from '@angular/common';
    
    @Component({
      selector: 'my-app',
     templateUrl: './my-app.component.html',
      styleUrls: ['./my-app.component.scss']
    })
    export class MyComponent() implements OnInit {
    
      constructor(private datePipe: DatePipe) {}
    
      ngOnInit(): void {
        let date = this.transformDate('2023-02-01T06:40:49.562Z');
        console.log('date:',date);
      }
    
      transformDate(date: string) {
        return this.datePipe.transform(date, 'yyyy-MM-dd');
      }
    }

其他回答

是的,通过使用简单的自定义管道就可以实现。使用自定义管道的优点是,如果将来需要更新日期格式,我们可以去更新单个文件。

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
  transform(value: string) {
    const datePipe = new DatePipe("en-US");
    value = datePipe.transform(value, 'MMM-dd-yyyy');

    return value;
  }
}
{{currentDate | dateFormatPipe }}

你可以在任何地方使用这个管道,组件,服务等等。

例如:

import { Component } from '@angular/core';
import {dateFormatPipe} from './pipes'

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);
}

这个答案现在已经过时了

建议使用其他答案的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');

我使用这个方法:

 import { Component, OnInit } from '@angular/core';
    import {DatePipe} from '@angular/common';
    
    @Component({
      selector: 'my-app',
     templateUrl: './my-app.component.html',
      styleUrls: ['./my-app.component.scss']
    })
    export class MyComponent() implements OnInit {
    
      constructor(private datePipe: DatePipe) {}
    
      ngOnInit(): void {
        let date = this.transformDate('2023-02-01T06:40:49.562Z');
        console.log('date:',date);
      }
    
      transformDate(date: string) {
        return this.datePipe.transform(date, 'yyyy-MM-dd');
      }
    }

您可以使用formatDate()来格式化服务或组件中的日期。 语法:

    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');

你可以在这里看到所有其他预定义的格式选项,

https://angular.io/api/common/DatePipe

如果想在组件中使用自定义管道,可以添加

@Injectable({
  providedIn: 'root'
})

注释到自定义管道。 然后,您可以将其作为一项服务使用