Iñigo
Iñigo

Reputation: 2016

Angular Material datepicker value format

I have a Datepicker input like this:

<mat-form-field class="example-full-width">
    <input #startDate matInput [matDatepicker]="picker" (dateInput)="first($event.value)" placeholder="Enter date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

When the input changes, the first funtion receives the $event.value date in this format:

Tue Apr 09 2019 00:00:00 GMT+0200

And I need this one (AAAA-MM-DD):

2019-04-09

Is there any way to change the Datepicker's output value whitout parsing it by hand? Thanks.

Upvotes: 3

Views: 12940

Answers (3)

Quan Vo
Quan Vo

Reputation: 1336

With Material DatePicker, you could choose MatNativeDateModule or MatMomentDateModule as date implementation. In your case, I suggest you take the MatMomentDateModule, at that time the $event.value will be a Moment object, which could be easily converted to a string.

Here is my solution

app.module.ts

@NgModule({
  imports: [
    ...,
    MatDatepickerModule,
    MatMomentDateModule
  ]

your.component.ts

<input #startDate matInput [matDatepicker]="picker" (dateInput)="first($event.value.format('YYYY-MM-D'))" placeholder="Enter date">

Here is a working StackBlitz.

Upvotes: 3

Andrei Tuduce
Andrei Tuduce

Reputation: 31

Create a custom format template for example

export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'YYYY-MM-DD',
    monthYearLabel: 'YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'YYYY',
  },
};

This will be your format and you will have to import it in your component providers

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

  //...

providers: [
   {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
 ],

I hope this will help you.

Upvotes: 1

rikg93
rikg93

Reputation: 1269

You could use DatePipe.

In your component:

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

constructor(private datePipe : DatePipe)
{

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

You must add also in app.module.

I hope this help you!

Upvotes: 2

Related Questions