Introduction
In modern web applications, date and time formatting is a crucial part of user interfaces. Whether you’re showing creation dates, timestamps, or scheduling information, displaying dates in a readable and user-friendly format improves both clarity and experience.
Angular provides a built-in DatePipe that makes date and time formatting simple and efficient. Instead of manually manipulating JavaScript’s Date
object, you can use the DatePipe
directly in your templates or programmatically in your components.
This post will guide you through everything you need to know about Angular’s DatePipe, including its syntax, formats, parameters, localization, and customization.
Table of Contents
- Introduction to Angular Pipes
- What is DatePipe?
- Importing and Using DatePipe
- Basic Syntax of DatePipe
- Displaying Current Date in Templates
- Built-in Predefined Date Formats
- Using Custom Date Formats
- Formatting Time with DatePipe
- Displaying Dates with Timezone
- Using DatePipe in TypeScript Code
- Transform Method of DatePipe
- Formatting Dynamic Date Values
- DatePipe and Localization (Locale Support)
- Changing the Default Locale in Angular
- Example: Displaying Dates in Different Locales
- Handling UTC and Timezone Differences
- Common Format Tokens
- Using Safe Navigation with DatePipe
- Handling Null or Undefined Dates
- Applying DatePipe in Tables and Lists
- Real-World Example: Formatting API Dates
- Combining DatePipe with AsyncPipe
- Using DatePipe with Custom Components
- Performance Considerations
- Custom Pipes vs DatePipe
- Testing DatePipe in Unit Tests
- Best Practices for Using DatePipe
- Complete Example: Date Formatting Dashboard
- Summary
- Conclusion
1. Introduction to Angular Pipes
In Angular, pipes are special functions that transform data before displaying it in the template.
They are denoted by the pipe (|
) character.
Example:
<p>{{ username | uppercase }}</p>
Here, the built-in uppercase
pipe transforms text into uppercase letters.
Similarly, Angular provides many pipes such as:
currency
date
decimal
percent
json
async
The DatePipe
is one of the most commonly used and powerful pipes.
2. What is DatePipe?
DatePipe transforms a date object, timestamp, or ISO string into a human-readable string format.
Example:
<p>{{ today | date:'fullDate' }}</p>
If today
is new Date(2025, 9, 9)
, the output might be:
Thursday, October 9, 2025
3. Importing and Using DatePipe
You don’t need to import DatePipe
separately when using it in templates because it’s part of CommonModule, which is imported automatically in most Angular modules.
If you want to use it in a component TypeScript file, then import it explicitly:
import { DatePipe } from '@angular/common';
constructor(private datePipe: DatePipe) {}
4. Basic Syntax of DatePipe
The basic syntax of using DatePipe in an Angular template is:
{{ dateValue | date:format:timezone:locale }}
- dateValue – A Date object, timestamp, or ISO string.
- format – The desired date format (e.g.,
short
,fullDate
,dd/MM/yyyy
). - timezone – Optional timezone (e.g.,
'+0500'
,'UTC'
). - locale – Optional locale identifier (e.g.,
'en-US'
,'fr'
).
5. Displaying Current Date in Templates
To display today’s date:
Component:
today = new Date();
Template:
<p>{{ today | date }}</p>
By default, Angular applies the mediumDate
format.
Example output:
Oct 9, 2025
6. Built-in Predefined Date Formats
Angular provides several predefined date formats:
Format | Description | Example Output |
---|---|---|
short | Short date/time | 9/9/25, 3:00 PM |
medium | Medium date/time | Oct 9, 2025, 3:00:00 PM |
long | Long date/time | October 9, 2025 at 3:00:00 PM GMT+5 |
full | Full date/time | Thursday, October 9, 2025 at 3:00:00 PM GMT+05:00 |
shortDate | Short date | 9/9/25 |
mediumDate | Medium date | Oct 9, 2025 |
longDate | Long date | October 9, 2025 |
fullDate | Full date | Thursday, October 9, 2025 |
shortTime | Short time | 3:00 PM |
mediumTime | Medium time | 3:00:00 PM |
Example:
<p>{{ today | date:'shortDate' }}</p>
<p>{{ today | date:'fullDate' }}</p>
<p>{{ today | date:'mediumTime' }}</p>
7. Using Custom Date Formats
You can define custom formats using tokens like dd
, MM
, yyyy
, hh
, mm
, and a
.
Example:
<p>{{ today | date:'dd/MM/yyyy' }}</p>
<p>{{ today | date:'EEEE, MMMM d, y' }}</p>
<p>{{ today | date:'hh:mm a' }}</p>
Output:
09/10/2025
Thursday, October 9, 2025
03:00 PM
8. Formatting Time with DatePipe
DatePipe is not limited to dates — it also handles time formatting.
<p>{{ today | date:'hh:mm:ss a' }}</p>
<p>{{ today | date:'HH:mm:ss' }}</p>
hh
= 12-hour formatHH
= 24-hour formata
= AM/PM indicator
9. Displaying Dates with Timezone
You can specify a timezone manually.
<p>{{ today | date:'medium':'UTC' }}</p>
<p>{{ today | date:'short':'GMT+0500' }}</p>
This helps when working with users across multiple regions.
10. Using DatePipe in TypeScript Code
If you want to format a date in your component logic (not template), you can use the DatePipe
service.
import { DatePipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-date-demo',
template: <p>{{ formattedDate }}</p>
,
providers: [DatePipe]
})
export class DateDemoComponent {
formattedDate: string | null;
constructor(private datePipe: DatePipe) {
const now = new Date();
this.formattedDate = this.datePipe.transform(now, 'fullDate');
}
}
11. Transform Method of DatePipe
The transform()
method accepts:
transform(value: any, format?: string, timezone?: string, locale?: string): string | null
Example:
this.datePipe.transform('2025-10-09', 'dd/MM/yyyy');
12. Formatting Dynamic Date Values
When dealing with API data, you often get ISO strings like 2025-10-09T12:45:00Z
.
You can format them directly using DatePipe.
<p>{{ user.createdAt | date:'medium' }}</p>
13. DatePipe and Localization (Locale Support)
Angular’s DatePipe supports localization — meaning it can display date and time formats according to different countries and languages.
Example:
<p>{{ today | date:'fullDate':'':'fr' }}</p>
<p>{{ today | date:'fullDate':'':'de' }}</p>
This displays the same date in French and German formats.
14. Changing the Default Locale in Angular
To change the global locale for the entire app:
Import locale data in app.module.ts
:
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);
Provide Locale:
@NgModule({
providers: [{ provide: LOCALE_ID, useValue: 'fr' }]
})
export class AppModule {}
Now all DatePipes use French locale by default.
15. Example: Displaying Dates in Different Locales
<p>US: {{ today | date:'fullDate':'':'en-US' }}</p>
<p>UK: {{ today | date:'fullDate':'':'en-GB' }}</p>
<p>FR: {{ today | date:'fullDate':'':'fr' }}</p>
<p>JP: {{ today | date:'fullDate':'':'ja' }}</p>
Each line will display the same date differently based on the locale’s date format.
16. Handling UTC and Timezone Differences
Sometimes, your backend sends UTC timestamps.
Angular’s DatePipe can convert them easily.
<p>{{ utcDate | date:'medium':'UTC' }}</p>
<p>{{ utcDate | date:'medium':'GMT+0500' }}</p>
If you want to always display local time, omit the timezone argument.
17. Common Format Tokens
Token | Description | Example |
---|---|---|
y | Year | 2025 |
yy | Two-digit year | 25 |
yyyy | Full year | 2025 |
M | Month number | 9 |
MM | Two-digit month | 09 |
MMM | Abbreviated month | Oct |
MMMM | Full month | October |
d | Day | 9 |
dd | Two-digit day | 09 |
EEEE | Full weekday | Thursday |
h / hh | Hour (12-hour) | 03 |
H / HH | Hour (24-hour) | 15 |
mm | Minutes | 45 |
ss | Seconds | 30 |
a | AM/PM | PM |
z | Timezone | GMT+5 |
18. Using Safe Navigation with DatePipe
If the date might be undefined (for example, when fetching async data), use Angular’s safe navigation operator (?.
).
<p>{{ user?.joinedAt | date:'medium' }}</p>
This prevents runtime errors before data is available.
19. Handling Null or Undefined Dates
To handle missing dates gracefully:
<p>{{ user?.createdAt ? (user.createdAt | date:'medium') : 'No date available' }}</p>
20. Applying DatePipe in Tables and Lists
DatePipe is often used inside tables to format data dynamically.
<table>
<tr *ngFor="let order of orders">
<td>{{ order.id }}</td>
<td>{{ order.date | date:'shortDate' }}</td>
<td>{{ order.total }}</td>
</tr>
</table>
21. Real-World Example: Formatting API Dates
When fetching API data, you may get timestamps like 2025-10-09T10:30:00Z
.
You can display them using DatePipe.
Service:
getOrders() {
return this.http.get('/api/orders');
}
Template:
<tr *ngFor="let order of orders">
<td>{{ order.createdAt | date:'short' }}</td>
</tr>
22. Combining DatePipe with AsyncPipe
If data comes from an Observable, you can combine date
and async
pipes.
<p>{{ orderService.getOrderDate() | async | date:'medium' }}</p>
23. Using DatePipe with Custom Components
You can format inputs, display user history, or show last updated times using DatePipe inside reusable components.
Example:
<p>Last updated: {{ lastUpdated | date:'short' }}</p>
24. Performance Considerations
- DatePipe executes on every change detection cycle.
- Use pure pipes for static values to optimize rendering.
- Avoid heavy computations inside the template.
25. Custom Pipes vs DatePipe
If your app needs special formatting (e.g., “2 hours ago”), you can create a custom pipe.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'timeAgo' })
export class TimeAgoPipe implements PipeTransform {
transform(value: Date): string {
const diff = Date.now() - new Date(value).getTime();
const minutes = Math.floor(diff / 60000);
if (minutes < 60) return ${minutes} minutes ago
;
const hours = Math.floor(minutes / 60);
return ${hours} hours ago
;
}
}
Usage:
<p>{{ user.createdAt | timeAgo }}</p>
26. Testing DatePipe in Unit Tests
You can write simple unit tests to verify DatePipe behavior.
import { DatePipe } from '@angular/common';
describe('DatePipe', () => {
const datePipe = new DatePipe('en-US');
it('should format date correctly', () => {
expect(datePipe.transform('2025-10-09', 'dd/MM/yyyy')).toBe('09/10/2025');
});
});
27. Best Practices for Using DatePipe
- Always use ISO date strings for consistency.
- Use locale identifiers for internationalization.
- Avoid heavy formatting inside large loops for performance.
- Apply safe navigation for async or nullable data.
- Use DatePipe in services if the format is reused across components.
- Use custom pipes for relative time formatting.
- Store timezone preferences if your app supports multiple regions.
28. Complete Example: Date Formatting Dashboard
Component:
import { Component } from '@angular/core';
@Component({
selector: 'app-date-dashboard',
templateUrl: './date-dashboard.component.html'
})
export class DateDashboardComponent {
today = new Date();
meeting = new Date('2025-10-15T10:30:00Z');
}
Template:
<h2>DatePipe Demo</h2>
<p>Default Format: {{ today | date }}</p>
<p>Short Date: {{ today | date:'shortDate' }}</p>
<p>Medium Time: {{ today | date:'mediumTime' }}</p>
<p>Custom Format: {{ meeting | date:'EEEE, MMM d, y, h:mm a' }}</p>
<p>UTC Time: {{ meeting | date:'medium':'UTC' }}</p>
<p>French Locale: {{ today | date:'fullDate':'':'fr' }}</p>
Leave a Reply