3

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.

1
  • You mean without using the JavaScript Date method? No, I don't think so. You can check the api at Angular Datepicker Commented Apr 8, 2019 at 13:40

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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!

1 Comment

1. Angular already has a date pipe 2. Even if your solution fits what he is looking for, and it works, you didn't show him how to use the pipe. 3. Pipes do not work with values passed in from template to component through a function expression in angular
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.