我正在使用日期管道来格式化我的日期,但如果没有解决方案,我就无法得到我想要的确切格式。我理解管道是错误的还是不可能的?

//our root app component
import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <h3>{{date | date: 'ddMMyyyy'}}, should be 
      {{date | date: 'dd'}}/{{date | date:'MM'}}/{{date | date: 'yyyy'}}</h3>

    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2'
    this.date = new Date();
  }
}

plnkr view)


当前回答

你也可以使用momentjs来做这类事情。Momentjs最擅长用JavaScript解析、验证、操作和显示日期。

我使用了Urish的这个管道,它对我来说很好:

https://github.com/urish/angular2-moment/blob/master/src/DateFormatPipe.ts

在args参数中,你可以输入日期格式,如:"dd/mm/yyyy"

其他回答

在Angular 2.0.0-rc中修复了管道日期格式的错误。2,这个Pull Request。

现在我们可以用传统的方法:

{{valueDate | date: 'dd/MM/yyyy'}}

例子:

当前版本:

Angular 13示例


旧版本:

示例:Angular 8.x.x

Angular 7.x示例

示例Angular 6.x

Angular 4.x

Angular 2.x示例


更多信息请参阅DatePipe文档

在我的例子中,我在组件文件中使用:

import {formatDate} from '@angular/common';

// Use your preferred locale
import localeFr from '@angular/common/locales/fr';
import { registerLocaleData } from '@angular/common';

// ....

displayDate: string;
registerLocaleData(localeFr, 'fr');
this.displayDate = formatDate(new Date(), 'EEEE d MMMM yyyy', 'fr');

在组件HTML文件中

<h1> {{ displayDate }} </h1>

这对我来说很好;-)

我认为这是因为区域设置硬编码到DatePipe中。请看这个链接:

https://github.com/angular/angular/blob/master/modules/%40angular/common/src/pipes/date_pipe.ts

现在没有办法通过配置来更新这个区域设置。

如果有人在看时间和时区,这是给你的

 {{data.ct | date :'dd-MMM-yy h:mm:ss a '}}

在日期和时间格式的末尾添加z表示时区

 {{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}

更新:

鉴于Moment.js已弃用,这个答案不再有效。目前,当我必须格式化一些日期,根据任务,我使用Javascript date或date-fns是一个很好的替代Moment.js日期计算(添加或删除日期,等等…)

不要用这个:

import { Pipe, PipeTransform } from '@angular/core'
import * as moment from 'moment'

@Pipe({
   name: 'formatDate'
})
export class DatePipe implements PipeTransform {
   transform(date: any, args?: any): any {
     let d = new Date(date)
     return moment(d).format('DD/MM/YYYY')
      
   }
}

在视图中: {{date | formatDate}}