ArticleZip > Angular 2 Material 2 Datepicker Date Format

Angular 2 Material 2 Datepicker Date Format

Angular 2 Material 2 Datepicker Date Format

When working with Angular applications, handling dates is a common requirement. The Material 2 Datepicker in Angular 2 provides a simple yet powerful way to integrate date selection functionality. One important aspect to customize is the date format displayed in the Datepicker. In this article, we will guide you through configuring the date format in the Angular 2 Material 2 Datepicker to suit your specific needs.

By default, the Material 2 Datepicker in Angular 2 uses the format defined by the locale settings of your application. However, you may want to override this default format to display dates in a different way. To achieve this, we can utilize the Moment.js library to define a custom date format.

First, make sure you have Moment.js installed in your project. You can do this by running the following command in your terminal:

Bash

npm install moment --save

Once Moment.js is installed, you can import it into your Angular component where you are using the Material 2 Datepicker:

Javascript

import * as moment from 'moment';

Next, within your component, declare a variable to hold your custom date format. For example, if you wish to display dates in the format 'MM/DD/YYYY', you can define the format as follows:

Javascript

customDateFormat = 'MM/DD/YYYY';

Now, in the template where you have the Material 2 Datepicker implemented, you can pass this custom format to the `matDatepicker` input property. Here's an example of how you can do this:

Html

In the component class, bind the custom date format to the `matDatepicker` input property using Moment.js:

Javascript

import { Moment } from 'moment';

public date = new FormControl(moment());

ngOnInit() {
    this.date.valueChanges.subscribe((value: Moment) => {
        this.date.setValue(value.format(this.customDateFormat), { emitEvent: false });
    });
}

By subscribing to the `valueChanges` event of the date control, you can format the selected date according to your custom format before setting it.

That's it! By following these steps, you can easily customize the date format displayed in the Angular 2 Material 2 Datepicker to meet your requirements. Experiment with different date formats and make the Datepicker suit your application's style and user preferences. Happy coding!