Angular Material Datepicker text input formatting

Upon using the datepicker to select a date, everything functions smoothly and the date appears in the correct format: DD/MM/YYYY

However, if I manually input a date in the DD/MM/YYYY format, the datepicker automatically changes it to MM/DD/YYYY, mistaking the first value DD for a month.

Is there a way to ensure that manual inputs are recognized as DD/MM/YYYY instead of MM/DD/YYYY?

Thank you!

<mat-form-field class="datepickerformfield" floatLabel="never">
    <input matInput class="dp" formControlName="fpresentaciondesde" [matDatepicker]="picker5" placeholder="DD/MM/YYYY" required>
    <mat-datepicker-toggle matSuffix [for]="picker5"></mat-datepicker-toggle>
    <mat-datepicker #picker5></mat-datepicker>
</mat-form-field>

Answer №1

To handle date formatting in a customized way, you can create your own date adapter like the following example:

export class CustomDateAdapter extends NativeDateAdapter {

    parse(value: any): Date | null {

    if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
       const str = value.split('/');

      const year = Number(str[2]);
      const month = Number(str[1]) - 1;
      const date = Number(str[0]);

      return new Date(year, month, date);
    }
    const timestamp = typeof value === 'number' ? value : Date.parse(value);
    return isNaN(timestamp) ? null : new Date(timestamp);
  }

  format(date: Date, displayFormat: Object): string {
    date = new Date(Date.UTC(
      date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(),
      date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
    displayFormat = Object.assign({}, displayFormat, { timeZone: 'utc' });

    const dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
    return dtf.format(date).replace(/[\u200e\u200f]/g, '');
  }

}

Then integrate it into your application by adding the following code:

@NgModule({
    ....
    providers: [
        { provide: DateAdapter, useClass: CustomDateAdapter }
    ]
})

Check out the demo here!

Answer №2

This code snippet demonstrates how to implement a custom date format in Angular Material DatePicker.

<mat-form-field>
<input matInput placeholder=”Select Date” [matDatepicker]=”datepickerRef” name=”datepicker” ngModel #dateCtrl=”ngModel” required readonly/>
<mat-datepicker-toggle [for]=”datepickerRef” matSuffix></mat-datepicker-toggle>
<mat-datepicker #datepickerRef></mat-datepicker>
<mat-error *ngIf=”dateCtrl.errors?.required && deptCtrl.touched”>Choose a Date</mat-error>
</mat-form-field>

The code above is from the file format-datepicker.ts, which includes a helper function for formatting dates.

import { NativeDateAdapter } from ‘@angular/material’;
import { MatDateFormats } from ‘@angular/material/core’;
export class AppDateAdapter extends NativeDateAdapter {
  format(date: Date, displayFormat: Object): string {
    if (displayFormat === ‘input’) {
      let day: string = date.getDate().toString();
      day = +day < 10 ? ‘0’ + day : day;
      let month: string = (date.getMonth() + 1).toString();
      month = +month < 10 ? ‘0’ + month : month;
      let year = date.getFullYear();
      return `${day}-${month}-${year}`;
    }
    return date.toDateString();
  }
}
export const APP_DATE_FORMATS: MatDateFormats = {
  parse: {
    dateInput: { month: ‘short’, year: ‘numeric’, day: ‘numeric’ },
  },
  display: {
    dateInput: ‘input’,
    monthYearLabel: { year: ‘numeric’, month: ‘numeric’ },
    dateA11yLabel: { year: ‘numeric’, month: ‘long’, day: ‘numeric’
    },
    monthYearA11yLabel: { year: ‘numeric’, month: ‘long’ },
  }
};

To use this implementation, include it within the providers tag as shown below:

import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from 'src/app/shared/format-datepicker';
@Component({
  providers: [
    {provide: DateAdapter, useClass: AppDateAdapter},
    {provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
  ]
})

For more details on this implementation, refer to the article at here. It has been tested and verified to work successfully!

Answer №3

Accepts input in the format DD.MM.YY and DD.MM.YYYY

File ru-date-adapter.ts

import { Injectable } from "@angular/core";
import { MatDateFormats, NativeDateAdapter } from "@angular/material/core";

@Injectable()
export class DateAdapterRus extends NativeDateAdapter {
    
    override getFirstDayOfWeek(): number {
        return 1;
    }

    override parse(value: any, parseFormat?: any): Date | null{
        if (parseFormat == 'DD.MM.YYYY' || parseFormat == 'DD.MM.YY'){
            let dateParts = value.match(/(\d{1,2}).(\d{1,2}).(\d{2,4})/)
            if (dateParts) {
                let day = dateParts[1]
                let month = dateParts[2]
                let year = dateParts[3]
                if (year.length == 2){
                    let currentDate = new Date()
                    year = currentDate.getFullYear().toString().slice(0,2) + year
                }
                let data = new Date(Date.parse(`${year}-${month}-${day}`))
                return data
            }
        }
        let data = super.parse(value, parseFormat)
        return data
    }
}

export const RUS_DATE_FORMATS: MatDateFormats = {
    parse: {
        dateInput: 'DD.MM.YYYY',
    }, 
    display: {
        dateInput: 'DD.MM.YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM-YYYY',
    },
}

Module file app.module.ts

    providers: [
        {
            provide: DateAdapter, useClass: DateAdapterRus
        },
        {
            provide: MAT_DATE_FORMATS, useValue: RUS_DATE_FORMATS
        },
     ]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

TypeScript: Extending a Generic Type with a Class

Although it may seem generic, I am eager to create a class that inherits all props and prototypes from a generic type in this way: class CustomExtend<T> extends T { constructor(data: T) { // finding a workaround to distinguish these two ...

The Authorization header in POST and PATCH fetch requests is stripped by Typescript

I have developed an API in C# that utilizes JWT tokens for authorization. On the frontend, I store these tokens in local storage and retrieve them when making a request. GET or DELETE requests work seamlessly, as I can verify through console.log() that t ...

Use the event emitter to close the mat-sidebar

Utilizing the material-sidebar for displaying the mobile menu, I aim to have the sidebar close when any item in the menu is clicked. To achieve this functionality, I utilize the EventEmitter() function to trigger the closure of the sidebar from the child ...

Monitoring the parent's CSS attribute in Angular 2

One of my directives dynamically adds the number of pixels corresponding to its parent element's right CSS attribute. import { Directive, ElementRef, AfterViewInit } from "angular2/core" @Directive({ selector: "[d]" }) export class Positioni ...

Ensuring complete type safety by passing an object literal as a function parameter to a TypeScript type with rigorous type validation

I have a script written in JavaScript that I am currently converting to TypeScript. The code I am working with includes the following: const shapes = []; shapes.push({ name: 'Circle', radius: 12 }); shapes.push({ name: 'Rectangle', wid ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Having trouble handling responses in nodejs when using inversifyjs

Currently, I am utilizing nodejs alongside typescript, typeorm, and inversify for managing dependency injection. I am also using inversify express utils to handle controllers. However, I am facing an issue where sending a response inside the then or catch ...

struggling with utilizing JSON.stringify()

I have been attempting to log an object's attributes using console.log(JSON.stringify(object)) in TypeScript and then converting it to JavaScript. However, when I call the function, nothing gets logged. I am creating the object with the parameters of ...

retrieve the initial subarray from the array using rxjs

Looking to extract the first array from a subarray, my current setup is as follows: Map: map; Map() { Service }); } This is the interface structure: export interface map { } Encountering an error message: ERROR TypeError: ...

Having trouble setting up mongodb-memory-server 8 to work with jest

I am currently working on integrating the latest version of mongodb-memory-server with jest on a node express server. While following the guide provided in the mongodb-memory-server documentation (), I encountered some gaps that I am struggling to fill in. ...

Fetching properties from an array of components

Hello, I'm currently working on a React component and facing an interesting challenge. Let's say I have an array structured like this: let data: {title: ReactNode}[] = [ {title: "test1"}, {title: <Component1 title="test2& ...

Angular - Set value only if property is present

Check if the 'rowData' property exists and assign a value. Can we approach it like this? if(this.tableObj.hasOwnProperty('rowData')) { this.tableObj.rowData = this.defVal.rowData; } I encountered an error when attempting this, specif ...

Ways to output a React component using TypeScript

Looking for guidance on how to print a React component using TypeScript when a button is clicked. I'm new to both React and TypeScript and would like to know how to achieve this functionality in my project. ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Issue arises with data types while utilizing the shadcn FormField element

Error: Type 'foo' cannot be assigned to type 'InputProps' Currently, I am attempting to create a reusable component named TextInput that encapsulates the Shadcn FormField component. The documentation specifies the need to pass a "field ...

What is the process of converting the Object type returned from an Observable to an array of objects in Angular?

When utilizing the GET method to retrieve information, I have encountered a problem. Here is the code snippet: constructor(private http: HttpClient) { } items: Item[]; stuff: any[]; ngOnInit() { const url = ...; this.http.get(url) .subscribe(nex ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Displaying exclusively the country code in an Angular material-select component

This is the HTML code I am using: <mat-form-field style="width: 70px;margin-left: 50px;"> <mat-label>Select an option</mat-label> <mat-select (openedChange)="toogleCountry()" [(value)]="selected"> <mat-option value="+91" ...

Is there a way to bypass TypeScript decorators and instead use NestJS entities like typical types?

I am trying to find a way to work with TypeScript entities in NestJS without using decorators. Currently, I define my entity like this: import { PrimaryGeneratedColumn, Column, Entity } from 'typeorm'; @Entity() export class User { @PrimaryGe ...

What is the best way to retrieve entire (selected) objects from a multiselect feature in Angular?

I'm facing an issue with extracting entire objects from a multiselect dropdown that I have included in my angular template. Although I am able to successfully retrieve IDs, I am struggling to fetch the complete object. Instead, in the console, it dis ...