Angular HTML Display Date Format
Angular provides a convenient way to display dates in different formats within your HTML templates. You can achieve this using the built-in DatePipe
and its various options.
Using DatePipe
The DatePipe
is a powerful tool for formatting dates in Angular. Here's a simple example:
Today's date is: {{ today | date }}
In this code:
today
is a variable holding a Date object.| date
is the pipe operator that applies theDatePipe
to thetoday
variable.
By default, DatePipe
will display the date in the user's locale's default format. To customize the format, you can pass a format string as an argument to the date
pipe:
Today's date is: {{ today | date:'short' }}
Today's date is: {{ today | date:'medium' }}
Today's date is: {{ today | date:'long' }}
Today's date is: {{ today | date:'full' }}
Today's date is: {{ today | date:'dd/MM/yyyy' }}
Today's date is: {{ today | date:'EEEE, MMMM d, y' }}
Here are some common format options:
- short: This displays a short format, for example, 12/31/2023.
- medium: This displays a medium format, for example, Dec 31, 2023.
- long: This displays a long format, for example, December 31, 2023.
- full: This displays a full format, for example, Sunday, December 31, 2023.
- dd/MM/yyyy: This displays the date in a custom format.
- EEEE, MMMM d, y: Another custom format with weekday, month, day, and year.
You can find a complete list of supported format codes in the Angular documentation.
Implementing DatePipe in a Component
Here's an example of how you can use DatePipe
within a component:
import { Component } from '@angular/core';
@Component({
selector: 'app-date-display',
template: `
Today's date is: {{ today | date:'medium' }}
Yesterday's date was: {{ yesterday | date:'long' }}
`
})
export class DateDisplayComponent {
today: Date = new Date();
yesterday: Date = new Date(this.today.getTime() - (1000 * 60 * 60 * 24));
}
In this component:
- We import
Component
from@angular/core
. - We define a component with a
template
property. - We use the
DatePipe
within the template to format thetoday
andyesterday
dates.
Conclusion
The DatePipe
in Angular makes it easy to display dates in different formats within your HTML templates. By using the available format options, you can customize the date display to suit your specific needs.