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

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


当前回答

在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文档

其他回答

在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文档

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

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

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

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

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

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

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

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

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

在MacOS和iOS上,使用Typescript for Safari浏览器的Angular 2中,日期管道行为不正确。我最近遇到了这个问题。我不得不在这里使用moment js来解决这个问题。简而言之,我所做的…

在项目中添加momentjs npm包。 在xyz.component.html下面,(注意startDateTime是数据类型字符串)

(转换名称)

xyz.component.ts下,

Import * as moment from 'moment';

convertDateToString(dateToBeConverted: string) {
return moment(dateToBeConverted, "YYYY-MM-DD HH:mm:ss").format("DD-MMM-YYYY");
}