Ariel Spais
Ariel Spais

Reputation: 1

Strange Date format in mat-datepicker

Im having 2/1/2025 in this mat-datepicker but it shows the number as a fraction.

Im trying to see the date in the correct format.

Example

`    <mat-form-field appearance="outline" color="accent" class="w-100">        
        <input matInput 
               [matDatepicker]="picker" 
               formControlName="fechaNacimiento"               >
        <mat-datepicker-toggle matSuffix  [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker></mat-datepicker>
        <mat-error>El campo es obligatorio</mat-error>
      </mat-form-field>`

it seems to be something related to styles

Upvotes: 0

Views: 16

Answers (1)

Ian Carter
Ian Carter

Reputation: 2166

this can occur because under the hood Angular's mat-datepicker uses an input field and some browser might be extra smart and consider 2/1/2025 to be a mathematical expression (fraction).

ensure to set the MatDateFormats properly:

import { NgModule } from '@angular/core';
import { MatDateFormats, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core';
import { DateAdapter, MAT_DATE_LOCALE_PROVIDER } from '@angular/material/core';
import { NativeDateAdapter } from '@angular/material/core';

export const CUSTOM_DATE_FORMATS: MatDateFormats = {
    parse: {
        dateInput: 'MM/dd/yyyy',
    },
    display: {
        dateInput: 'MM/dd/yyyy',
        monthYearLabel: 'MMM yyyy',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM yyyy',
    }
};

@NgModule({
    providers: [
        { provide: MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS },
        { provide: MAT_DATE_LOCALE, useValue: 'en-US' }, // Ensure locale is correct
    ]
})

Upvotes: 0

Related Questions