如何用 angular 2 转换日期?

How to transform date with angular 2?

我想以这种格式转换来自服务器的日期 到这种格式 ('yyyy-mm-dd hh-mm-ss')

您可以直接附加字符串,这是最简单的数据解决方案

var string =  date.year + '-' + date.monthOfYear + '-' + date.dateOfMonth + ' ' + 'date.hourOfDay'+ '-' + date.minuteOfHour + '-' + date.secondOfMinute

您可以创建自己的管道:

@Pipe({name: 'myDate'})
export class MyDatePipe implements PipeTransform {
  transform(date: Object): string {
    return `${date.year}-${date.monthOfYear}-${date.dateOfMonth} ${date.hourOfDay}-${date.minuteOfHour}-${date.secondOfMinute}`;
  }
}

并像这样使用它:<div>{{ yourDateToFormat | myDate }}</div>

查看文档,很清楚:https://angular.io/docs/ts/latest/guide/pipes.html

<!--Import in app.module-->
import { DatePipe } from '@angular/common';
providers: [DatePipe]

<!--HTML-->
<input [ngModel]="startDate |date: 'yyyy-MM-dd'" name="startDate"/>
<button type="button" (click)="transformDate(startDate)">Aceptar</button>

<!--Component-->
import { DatePipe } from '@angular/common';

export class AppComponent {
   startDate: Date= new Date();

   constructor(private datepipe: DatePipe){}

  transformDate(date){        
         let transformdate: string;
         transformdate = this.datepipe.transform(date, 'MM/dd/yyyy');
         console.log(transformdate);
  }

}
html date= yyyy-MM-dd
Component Transform date=: MM/dd/yyy