Angular reactive forms with Material date picker enables the setting of date in the format of YYYY-MM-DDT00:00:00

I am trying to use Material DatePicker with Moment for date formatting while using reactive forms.

Here is the code where I set the value for NextDeliverDate in the .ts file:

loadData() {
    this.getSubscriptionData().subscribe((x) => {
      this.subscription = x;
      console.log(moment(this.subscription.NextDelivery).format('YYYY-MM-DDT00:00:00'));
      this.subscriptionForm.setValue({
        ID: this.subscription.ID || '',
        CustomerID: this.subscription.CustomerID || '',
        CustomerUserName: this.subscription.CustomerUserName || '',
        CustomerFirstName: this.subscription.CustomerFirstName || '',
        CustomerLastName: this.subscription.CustomerLastName || '',
        AddressID: this.subscription.AddressID || '',
        OrderID: this.subscription.OrderID || '',
        PaymentID: this.subscription.PaymentID || '',
        ProductID: this.subscription.ProductID || '',
        Quantity: this.subscription.Quantity || 0,
        Price: this.subscription.Price || 0,
        Total: this.subscription.Total || 0,
        FrequencyWeeks: this.subscription.FrequencyWeeks || 0,
        FranchiseID: this.subscription.FranchiseID || 0,
        NextDelivery: moment(this.subscription.NextDelivery).format('YYYY-MM-DDT00:00:00') ,        
        Active: this.subscription.Active || false,
        PaymentExpired: this.subscription.PaymentExpired || false,
        OnHold: this.subscription.OnHold || false,
        StartDate: this.subscription.StartDate || Date.now(),
        EndDate: this.subscription.EndDate || null,
        ZipCode: this.subscription.ZipCode || '',
      });
    });
  }

And here is the HTML code:

<div class="form-group row">
                            <label for="NextDelivery"
                                   class="col-sm-3 control-label font-weight-bold mt-1">NextDelivery</label>
                            <div class="col-sm-9">
                                <input type="text" formControlName="NextDelivery" class="form-control"
                                       id="NextDelivery" matInput [matDatepicker]="picker"/>
                                       <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
                                       <mat-datepicker #picker></mat-datepicker>
                            </div>
                        </div>

When I check the console, it shows the date as: 2025-06-19T00:00:00. However, in the input text box, it displays the date as: 6/19/2025.

Answer №1

Here is some additional code you can include:

import {MomentDateAdapter} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material';

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

If the material-moment-adapter or moment packages are not available in your project, make sure to install them using npm.

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

"The ion-label in Ionic2 is cutting off some of the text and not displaying it

I'm currently facing an issue with ion-label inside ion-item. The description is not properly displaying and instead, it shows dot-dot.. ..I need the entire text to be visible. Is there any solution available? <ion-card *ngFor="let product of prod ...

The property 'owlDateTimeTrigger' cannot be bound to 'span' as it is not recognized

I have integrated the OwlDateTimeModule into my smart-table-datepicker component. Although I imported it in my smart-table-datepicker.module file, I am still encountering errors. What could be causing this issue? smart-table-datepicker.module.ts import { ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

What is the best way to access an HtmlElement from an Angular component when outside of the

I've been researching extensively, but all the solutions I've found involve retrieving HTMLElement within the component itself or in other components. I am looking to retrieve HTMLElement from an Angular Component within a helper function or so ...

Customize the appearance of parent components based on the content of their child elements

I am currently working on a component that contains multiple instances, each with its own unique internal component (acting as a modal wrapper). I need to customize the size of each modal instance independently. How can I achieve this customization when th ...

Long wait times for Angular 2 applications to load

My Angular 2 app is experiencing slow loading times, almost 8 seconds. Upon investigation, I discovered that the longest load time is attributed to rxjs. The app makes numerous requests to rxjs/observable, rxjs/add and rxjs/operator. How can I enhance the ...

Displaying notification in Ionic 2

Whenever I click on the register button, if I fill out all the fields I am taken to the regsuccess page. Otherwise, I receive a message saying to fill in all required fields. However, I want to display an alert message using Ionic2 and TypeScript. HTML: ...

How to extract a JavaScript object from an array using a specific field

When dealing with an array of objects, my goal is to choose the object that has the highest value in one of its fields. I understand how to select the value itself: Math.max.apply(Math, list.map(function (o) { return o.DisplayAQI; })) ... but I am unsur ...

Encountering a Geolocation API issue during the troubleshooting of an Angular application on

Currently, I'm in the process of developing an angular application that utilizes the GeoLocation API to retrieve user location. To achieve this, I make use of the navigator.geolocation.getCurrentPosition() function. Surprisingly, everything works perf ...

Angular TimeTracker for tracking time spent on tasks

I need help creating a timer that starts counting from 0. Unfortunately, when I click the button to start the timer, it doesn't count properly. Can anyone assist me in figuring out why? How can I format this timer to display hours:minutes:seconds li ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...

Error: Unable to locate Angular2 Custom Service

I have implemented a custom service to populate a list of people in my HTML. Below is the code for my custom service: app.peopleListService.ts import { Injectable } from '@angular/core'; import { Person } from "../model/peopleModel"; @Injecta ...

Should moment.js be exposed to $rootScope for better coding practices?

After recently starting to work with an AngularJs app, I came across a situation in which a series of moment.js functions were being exported to $rootScope within the index.js file. The intention behind this was to make these functions easily accessible fr ...

Issue: The --outFile flag only supports 'amd' and 'system' modules

Encountering an issue while trying to compile an Angular project in Visual Studio Code using ng build and then serving it with ng serve Unfortunately, faced the following error message in both cases: The error 'Only 'amd' and 'syste ...

Looping Through RxJS to Generate Observables

I am facing the challenge of creating Observables in a loop and waiting for all of them to be finished. for (let slaveslot of this.fromBusDeletedSlaveslots) { this.patchSlave({ Id: slaveslot.Id, ...

Is it possible to create dynamic meta tags in Angular that will appear in a Twitter-style card preview?

My project involves building a dynamic website using a Java app that serves up a REST-ish JSON API along with an Angular9 front end. A key requirement is the ability to share specific URLs from the app on platforms like Twitter and Slack, which support Twi ...

Optimal methods for integrating an Angular application within an AngularJS application

Our extensive AngularJS application was initially developed 3 years ago and continues to receive new feature updates. I am keen on ensuring that these new features are written using the latest version of Angular. Converting the entire codebase is not feasi ...

Angular 10 and Typescript: Variables assigned within the change event become undefined

In my code, I initialize an Algolia input and set an onchange event to it. This initialization takes place in a service. algolia_data; random_var; this.http.post<any>('APIENDPOINT', formData).subscribe(data => { instance = places({ ...

Insert a new row into the table with a value that is taken from the input fields on the form

view image details I am working on a form that consists of 4 fields: Name, Last name, email, and role. There is also a button. When the button is clicked, the input from the above form should be added as a new row in a table below. ...

What is the solution for resolving the error message "Property '' does not exist on type 'typeof import'"?

Hi everyone, I'm a new Angular developer who is working on implementing authentication. I recently added the auth0-angular package to my project and now I'm encountering an error when creating a WebAuth() instance in my code editor (VS Code). Th ...