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

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

其他回答

在我的例子中,我使用的是格式为dd/MM/yyyy的日期字符串,并试图将其转换为不同的格式。

这个错误让我震惊。

在谷歌搜索之后,我发现日期字符串应该是iso认可的格式。

这对一些人来说可能很明显,但如果你想要这种日期格式

01.07.2022(在德国很常见)

你可以简单地这样做:

{{ myDate | date: "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');

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

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>

这对我来说很好;-)

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

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