How can I customize date and time format in ngx-mat-datetime-picker?

3 min read 06-10-2024
How can I customize date and time format in ngx-mat-datetime-picker?


Mastering Date and Time Formatting in ngx-mat-datetime-picker

The ngx-mat-datetime-picker library is a powerful tool for adding date and time selection functionality to your Angular applications. However, it's often necessary to customize the display format of the selected date and time to match your specific requirements. This article will guide you through the process of tailoring the date and time format to suit your needs.

The Scenario:

Imagine you're building a booking system where users need to select a date and time for their appointment. The ngx-mat-datetime-picker provides a user-friendly interface for this. However, you want to display the selected date in the "dd/MM/yyyy" format and the time in a 24-hour format.

Original Code (Default Format):

import { Component } from '@angular/core';

@Component({
  selector: 'app-booking',
  template: `
    <mat-form-field appearance="fill">
      <mat-label>Select Date and Time</mat-label>
      <input matInput [matDatepicker]="picker" [matDatepickerFilter]="dateFilter">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
  `,
})
export class BookingComponent {
  dateFilter = (d: Date) => {
    // ... filter logic
  };
}

Output: The default output displays the date in "MM/DD/YYYY" format and time in "HH:mm AM/PM" format.

Customizing the Format:

To achieve the desired date and time format, we'll use the matDatepickerFilter directive. This directive allows us to modify the displayed value using a function.

Modified Code (Custom Format):

import { Component } from '@angular/core';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';

@Component({
  selector: 'app-booking',
  template: `
    <mat-form-field appearance="fill">
      <mat-label>Select Date and Time</mat-label>
      <input matInput [matDatepicker]="picker" [matDatepickerFilter]="dateFilter" [(ngModel)]="selectedDateTime">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
    </mat-form-field>
    <p>Selected Date and Time: {{ selectedDateTime | date:'dd/MM/yyyy HH:mm' }}</p>
  `,
})
export class BookingComponent {
  selectedDateTime: Date;

  dateFilter = (d: Date): Date => {
    const day = d.getDate();
    const month = d.getMonth() + 1;
    const year = d.getFullYear();
    const hours = d.getHours();
    const minutes = d.getMinutes();
    return new Date(year, month - 1, day, hours, minutes);
  };
}

Output: The date is now displayed in "dd/MM/yyyy" format, and the time in the 24-hour format "HH:mm".

Explanation:

  1. matDatepickerFilter: We use this directive to customize the input value displayed in the date picker field.

  2. dateFilter function:

    • We extract the day, month, year, hour, and minute values from the selected date.
    • We construct a new Date object with the desired format.
    • This function ensures that the input field displays the selected date and time in the customized format.
  3. [(ngModel)]="selectedDateTime": We use two-way data binding to update the selectedDateTime variable with the selected date and time.

  4. {{ selectedDateTime | date:'dd/MM/yyyy HH:mm' }}: We use the built-in Angular date pipe to display the selected date and time in the desired format.

Key Considerations:

  • Localization: You can further customize the display based on user locale using the Intl.DateTimeFormat object. This enables adapting the date and time format to different regions.
  • Time Zone: The matDatepickerFilter function might need adjustment based on your specific time zone requirements.
  • Custom Formatting: If you need more complex formatting options beyond the standard date pipe, you can use libraries like Moment.js or Date-fns for advanced manipulation.

Conclusion:

Customizing the date and time format in ngx-mat-datetime-picker is straightforward with the matDatepickerFilter directive. By understanding the principles of date formatting and utilizing Angular's date pipe, you can effectively control the appearance of your date and time inputs to match your application's needs. Remember to consider localization and time zone aspects for a seamless user experience.