在AngularJS中,我能够在服务和控制器中使用过滤器(管道),使用类似于下面的语法:
$filter('date')(myDate, 'yyyy-MM-dd');
在Angular中,可以在服务/组件中像这样使用管道吗?
在AngularJS中,我能够在服务和控制器中使用过滤器(管道),使用类似于下面的语法:
$filter('date')(myDate, 'yyyy-MM-dd');
在Angular中,可以在服务/组件中像这样使用管道吗?
当前回答
这个答案现在已经过时了
建议使用其他答案的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');
其他回答
您可以使用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
这个答案现在已经过时了
建议使用其他答案的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');
}
}
如果想在组件中使用自定义管道,可以添加
@Injectable({
providedIn: 'root'
})
注释到自定义管道。 然后,您可以将其作为一项服务使用
像往常一样,在Angular中,你可以依赖依赖注入:
import { DatePipe } from '@angular/common';
class MyService {
constructor(private datePipe: DatePipe) {}
transformDate(date) {
return this.datePipe.transform(date, 'yyyy-MM-dd');
}
}
将DatePipe添加到模块中的提供者列表中;如果你忘记这样做,你会得到一个错误没有提供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 polyfill添加到你的项目中以避免任何问题。 请参阅相关问题以获得更详细的答案。