[date] 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();
  }
}

plnkr view

This question is related to date angular angular-pipe date-pipe

The answer is


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 have to pass the locale string as an argument to DatePipe.

var ddMMyyyy = this.datePipe.transform(new Date(),"dd-MM-yyyy");

Pre-defined format options:

1.      'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
2.      'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
3.      'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
4.      'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
5.      'shortDate': equivalent to 'M/d/yy' (6/15/15).
6.      'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
7.      'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
8.      'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
9.      'shortTime': equivalent to 'h:mm a' (9:03 AM).
10. 'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
11. 'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
12. 'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

add datepipe in app.component.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {DatePipe} from '@angular/common';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    DatePipe
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

If anyone can looking to display date with time in AM or PM in angular 6 then this is for you.

{{date | date: 'dd/MM/yyyy hh:mm a'}}

Output

enter image description here

Pre-defined format options

Examples are given in en-US locale.

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Reference Link


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>

Date pipes does not behave correctly in Angular 2 with Typescript for Safari browser on MacOS and iOS. I faced this issue recently. I had to use moment js here for resolving the issue. Mentioning what I have done in short...

  1. Add momentjs npm package in your project.

  2. Under xyz.component.html, (Note here that startDateTime is of data type string)

{{ convertDateToString(objectName.startDateTime) }}

  1. Under xyz.component.ts,

import * as moment from 'moment';

convertDateToString(dateToBeConverted: string) {
return moment(dateToBeConverted, "YYYY-MM-DD HH:mm:ss").format("DD-MMM-YYYY");
}

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

You can find more information about the date pipe here, such as formats.

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

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

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');
        }
    }
}

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


In my case, I use in component file:

import {formatDate} from '@angular/common';

// Use your preferred locale
import localeFr from '@angular/common/locales/fr';
import { registerLocaleData } from '@angular/common';

// ....

displayDate: string;
registerLocaleData(localeFr, 'fr');
this.displayDate = formatDate(new Date(), 'EEEE d MMMM yyyy', 'fr');

And in the component HTML file

<h1> {{ displayDate }} </h1>

It works fine for me ;-)


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.


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"


Angular: 8.2.11

<td>{{ data.DateofBirth | date }}</td>

Output: Jun 9, 1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy' }}</td>

Output: 09/06/1973

<td>{{ data.DateofBirth | date: 'dd/MM/yyyy hh:mm a' }}</td>

Output: 09/06/1973 12:00 AM


Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular-pipe

What is pipe() function in Angular Angular 4 Pipe Filter Format date as dd/MM/yyyy using pipes OrderBy pipe issue

Examples related to date-pipe

Format date as dd/MM/yyyy using pipes How to set locale in DatePipe in Angular 2?