38

This is the format of date I am getting when I am using angular material datepicker....Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time)

But I need date in (YYYY-MM-DD) or (YYYY-MM-DDTHH:mm) this format.

this is model class I am using to capture data from angular material form

export class FlightSchedule {

    constructor(
        public destination: string,
        public origin: string,
        public date: string,
        public limit: string
    ) {}

}

Please help me, I am unable to convert date in YYYY-MM-DD or YYYY-MM-DDTHH:mm format.

I am new to Angular

Thanks in advance

2
  • You are looking for to convert date that you received from datepicker or format date inside datepicker input? Nov 18, 2018 at 10:05
  • I am looking to convert date that I received from datepicker Nov 18, 2018 at 18:04

5 Answers 5

51

You need to provide an object containing the formats you wish to use. The object should look something like:

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

You then need to add that in to your providers array, like so:

  import { MAT_DATE_FORMATS } from '@angular/material/core';
  import { MomentDateAdapter } from '@angular/material-moment-adapter';

  //...

  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
  ],

Here is a StackBlitz demo to show it working

18
  • Thank you user184994, but I am unable to customize it in my project. This is my html datepicker format, which i am attaching it now Nov 18, 2018 at 17:56
  • <mat-form-field style="margin-top: 20px" class="demo-full-width" class="form-group"> <input required matInput [matDatepicker]="picker" name="date" placeholder="Date" class="form-control" [(ngModel)]="flightSchedule.date"> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker touchUi="true" #picker></mat-datepicker> </mat-form-field> Nov 18, 2018 at 17:56
  • Why are you unable to customize it?
    – user184994
    Nov 18, 2018 at 18:04
  • i believe I am having class="form-control" but in example it is [formControl]="date", so i unable to use date = new FormControl(moment()); in app component Nov 18, 2018 at 18:24
  • 1
    you can't manually change the date in this solution. it's behave wired
    – chami007
    Apr 26, 2019 at 9:44
27

No need to use MomentDateAdapter!

Here's my solution with the least amount of code and using the MAT_NATIVE_DATE_FORMATS.

  1. Declare your own date formats
import { MatDateFormats, MAT_NATIVE_DATE_FORMATS } from '@angular/material';

export const GRI_DATE_FORMATS: MatDateFormats = {
  ...MAT_NATIVE_DATE_FORMATS,
  display: {
    ...MAT_NATIVE_DATE_FORMATS.display,
    dateInput: {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    } as Intl.DateTimeFormatOptions,
  }
};
  1. Use them
@Component({
  selector: 'app-vacation-wizard',
  templateUrl: './vacation-wizard.component.html',
  styleUrls: ['./vacation-wizard.component.scss'],
  providers: [
    { provide: MAT_DATE_FORMATS, useValue: GRI_DATE_FORMATS },
  ]
})

Don't forget to set the appropriate language!

constructor(private readonly adapter: DateAdapter<Date>) {}
this.adapter.setLocale(this.translate.currentLang);

That's all!

4
  • what is this.adapter ? Aug 24, 2020 at 13:21
  • @gyozokudor material.angular.io/components/datepicker/…
    – Nato Boram
    Sep 10, 2020 at 18:52
  • this.adapter.setLocale("en-EN") goes into constructor body and adapter becomes a property of that class, that's whay this.adapter
    – Hrvoje T
    Nov 3, 2021 at 22:29
  • is it possible to set the format programmatically rather than hardcoding it?
    – chitgoks
    Oct 4 at 9:39
14
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material';
import { MomentDateModule, MomentDateAdapter } from '@angular/material-moment-adapter';

 export const DateFormats = {
            parse: {
                dateInput: ['YYYY-MM-DD']
            },
            display: {
                dateInput: 'YYYY-MM-DD',
                monthYearLabel: 'MMM YYYY',
                dateA11yLabel: 'LL',
                monthYearA11yLabel: 'MMMM YYYY',
            },
        };

    providers: [

        { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
          { provide: MAT_DATE_FORMATS, useValue: DateFormats }

      ],

add above code in your app.module. it is working perfectly for me.

3
  • 4
    @MSM any way to this this on run time
    – Rohitesh
    Jul 24, 2020 at 11:44
  • How can i show time also with this one like 2021-04-26T00:00:00 ? Mar 25, 2021 at 4:05
  • This only works for ng serve and not on production / run time.
    – Collin
    Sep 20, 2022 at 17:00
0

  modelChanged(date) {
    var theDate = new Date(Date.parse(date));
    const localDate = theDate.toLocaleString().split(" ");

    console.log(localDate);
  }
    <!--I had the same issue and found it that with javascript was simple approach
--->
    
    <mat-form-field class="example-full-width" appearance="fill">
          <mat-label>Choose a date</mat-label>
          <input
            matInput
            [matDatepicker]="picker"
            [(ngModel)]="date"
            (ngModelChange)="modelChanged($event)"
          />
          <mat-datepicker-toggle
            matSuffix
            [for]="picker"
          ></mat-datepicker-toggle>
          <mat-datepicker touchUi #picker color="primary"></mat-datepicker>
        </mat-form-field>

2
  • 3
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.
    – Doj
    Dec 16, 2020 at 12:37
  • Upvoted because it works and even it has no explanation, the code is very understandable. Dec 23, 2021 at 14:53
0

A shortcut way would be to create javascript date object and then format it to whatever format you want. Assuming you have [(ngModel)]="myDate" on your date input, you can do:

var formatedDate = new Date(this.myDate).toLocaleString();

This is short way of doing what u want :)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.