3

I am trying to format below date to following format MM-DD-YYYY in Angular 6. I had a look at simpler issues posted in SO and other sites as well but I am unable to resolve it.

I am using Material Angular DatePicker component.

Date picker gives me

Thu Oct 25 2018 00:00:00 GMT+0400 (Gulf Standard Time)

I want to format it to

MM-DD-YYYY

My code

<mat-form-field>
    <input matInput [min]="minDate" [matDatepicker]="date" [(ngModel)]="request.date | request.date: 'dd/MM/yyyy hh:mm a'" placeholder="Choose a date">
    <mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
    <mat-datepicker #date></mat-datepicker>
</mat-form-field>

I also tried with DatePipe module like below but nothing works

this.datePipe.transform(this.request.date,"MM-DD-YYYY")
halfer
  • 18,701
  • 13
  • 79
  • 158
Hemadri Dasari
  • 23,970
  • 25
  • 87
  • 133

4 Answers4

6

You can use DatePipe to format the date as per your requirement.

Import in main.module.ts

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

and add Datapipe in Providers array.

Then in related component import the same as

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

and in constructor

constructor(private datePipe : DatePipe)
{

}

and to use date pipe just use

this.datePipe.transform(your_date, 'MM-dd-yyyy');

Have a look at StackBlitz Example where I have consoled the date value in MM-dd-yyyy format.

Prashant Pimpale
  • 8,749
  • 6
  • 30
  • 70
1

Use the dateformat function from angular common.

Refer this answer

Prashant Pimpale
  • 8,749
  • 6
  • 30
  • 70
user3929590
  • 110
  • 9
1

Try this in the component you are using mat-datepicker

import { DateAdapter } from '@angular/material';

constructor(private dateAdapter: DateAdapter) { this.dateAdapter.setLocale('your locale'); }

Leandro Q
  • 91
  • 1
  • 2
0
import { formatDate } from '@angular/common';

formatDate(date, 'MMM, yyyy', 'en-US');

Angular 9