Format date as dd/MM/yyyy using pipes
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'}}
Examples:
Current Version:
Example Angular 8.x.x
Old Versions:
Example Angular 7.x
Example Angular 6.x
Example Angular 4.x
Example Angular 2.x
More info in documentation
DatePipe
Import DatePipe from angular/common and then use the below code:
var datePipe = new DatePipe();
this.setDob = datePipe.transform(userdate, 'dd/MM/yyyy');
where userdate will be your date string. See if this helps.
Make note of the lowercase for date and year :
d - date
M - month
y - year
EDIT
You have to pass locale
string as an argument to DatePipe, in latest angular. I have tested in angular 4.x
For Example:
var datePipe = new DatePipe('en-US');
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;
}
}
Template:
{{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
I always use Moment.js when I need to use dates for any reason.
Try this:
import { Pipe, PipeTransform } from '@angular/core'
import * as moment from 'moment'
@Pipe({
name: 'formatDate'
})
export class DatePipe implements PipeTransform {
transform(date: any, args?: any): any {
let d = new Date(date)
return moment(d).format('DD/MM/YYYY')
}
}
And in the view:
<p>{{ date | formatDate }}</p>