Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material date picker return Moment object instead of Date

I have a strange problem, in my html I defined-

    <mat-radio-button value="embargoed">
        <div>Everyone, limited by date</div>
        <mat-form-field *ngIf="data.selected === 'embargoed'">
            <mat-label>Available from date</mat-label>
            <input matInput [matDatepicker]="picker" #input [(ngModel)]="date">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
    </mat-radio-button>

in my comonent I initialized-

date = new Date();

I have an OnSubmit function that does-

onSubmit(){
    if (this.data.selected === 'embargoed') {
        this.data.date = this.date;
    }
}

In debud I can see that this.date is a Moment object instead of a Date object, any idea why?

like image 786
danda Avatar asked Sep 16 '25 02:09

danda


2 Answers

I found the reason. In my app.module.ts I had declared:

 {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS}
like image 129
danda Avatar answered Sep 18 '25 16:09

danda


From https://material.angular.io/components/datepicker/overview:

The type of values that the datepicker expects depends on the type of DateAdapter provided in your application. The NativeDateAdapter, for example, works directly with plain JavaScript Date objects. When using the MomentDateAdapter, however, the values will all be Moment.js instances.

Also: https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings:

The datepicker was built to be date implementation agnostic. This means that it can be made to work with a variety of different date implementations. However it also means that developers need to make sure to provide the appropriate pieces for the datepicker to work with their chosen implementation.

like image 24
Ruben Avatar answered Sep 18 '25 15:09

Ruben