Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Format date as dd/MM/yyyy using pipes

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();
}
}
by

3 Answers

rahul07
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.
RoliMishra
Pipe date format bug fixed in Angular 2.0.0-rc.2, this Pull Request.

Now we can do the conventional way:

{{valueDate | date: 'dd/MM/yyyy'}}
sandhya6gczb
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'}}

Login / Signup to Answer the Question.