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

//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)


当前回答

我正在使用这个临时解决方案:

import {Pipe, PipeTransform} from "angular2/core";
import {DateFormatter} from 'angular2/src/facade/intl';

@Pipe({
    name: 'dateFormat'
})
export class DateFormat implements PipeTransform {
    transform(value: any, args: string[]): any {
        if (value) {
            var date = value instanceof Date ? value : new Date(value);
            return DateFormatter.format(date, 'pt', 'dd/MM/yyyy');
        }
    }
}

其他回答

您可以使用一个简单的自定义管道来实现这一点。

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, 'dd/MM/yyyy');
        return value;
    }
}

模板:

{{currentDate | dateFormatPipe }}

使用自定义管道的好处是,如果你想在将来更新日期格式,你可以去更新你的自定义管道,它会反映每个地方。

自定义管道示例

唯一对我有用的灵感来自于这里: https://stackoverflow.com/a/35527407/2310544

对于纯粹的dd/MM/yyyy,这对我来说是可行的,angular 2 beta 16:

{{ myDate | date:'d'}}/{{ myDate | date:'MM'}}/{{ myDate | date:'y'}}

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

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

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

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

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

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

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

从angular/common中导入DatePipe,然后使用下面的代码:

var datePipe = new DatePipe();
    this.setDob = datePipe.transform(userdate, 'dd/MM/yyyy');

在哪里 userdate 将是您的日期字符串。 看看这是否有帮助。

注意小写的日期和年份:

d - date
M - month
y - year

EDIT

你必须将locale string作为参数传递给DatePipe,在latest angular中。我已经在angular 4.x中进行了测试

例如:

var datePipe = new DatePipe('en-US');