Format date as dd/MM/yyyy using pipes

2019-01-04 18:35发布

I'm using the date pipe to format my date, but I just can't get the exact format I want without a workaround. Am I understanding pipes wrongly or is just not possible?

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

12条回答
够拽才男人
2楼-- · 2019-01-04 19:03

If anyone looking with time and timezone, this is for you

 {{data.ct | date :'dd-MMM-yy h:mm:ss a '}}

add z for time zone at the end of date and time format

 {{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}
查看更多
▲ chillily
3楼-- · 2019-01-04 19:04

You can achieve this using by a simple custom pipe.

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 }}

Advantage of using a custom pipe is that, if you want to update the date format in future, you can go and update your custom pipe and it will reflect every where.

Custom Pipe examples

查看更多
姐就是有狂的资本
4楼-- · 2019-01-04 19:05

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

查看更多
Rolldiameter
5楼-- · 2019-01-04 19:15

You can also use momentjs for this sort of things. Momentjs is best at parse, validate, manipulate, and display dates in JavaScript.

I used this pipe from Urish, which works fine for me:

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

In the args parameter you can put your date format like: "dd/mm/yyyy"

查看更多
forever°为你锁心
6楼-- · 2019-01-04 19:18

The only thing that worked for me was inspired from here: https://stackoverflow.com/a/35527407/2310544

For pure dd/MM/yyyy, this worked for me, with angular 2 beta 16:

{{ myDate | date:'d'}}/{{ myDate | date:'MM'}}/{{ myDate | date:'y'}}
查看更多
Juvenile、少年°
7楼-- · 2019-01-04 19:22

I am using this Temporary Solution:

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');
        }
    }
}
查看更多
登录 后发表回答