【问题标题】:How to transform date with angular 2?如何用角度2转换日期?
【发布时间】:2017-09-25 23:40:36
【问题描述】:

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

【问题讨论】:

    标签: angular angular2-routing angular2-directives angular2-pipe


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以创建自己的管道:

      @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

      【讨论】:

        【解决方案3】:
        <!--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
        

        【讨论】:

          猜你喜欢
          • 2021-09-02
          • 1970-01-01
          • 2020-11-29
          • 1970-01-01
          • 1970-01-01
          • 2022-06-10
          • 1970-01-01
          • 2019-08-01
          • 2015-07-09
          相关资源
          最近更新 更多