Using the DatePipe in Angular

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

  1. Introduction to Angular Pipes
  2. What is DatePipe?
  3. Importing and Using DatePipe
  4. Basic Syntax of DatePipe
  5. Displaying Current Date in Templates
  6. Built-in Predefined Date Formats
  7. Using Custom Date Formats
  8. Formatting Time with DatePipe
  9. Displaying Dates with Timezone
  10. Using DatePipe in TypeScript Code
  11. Transform Method of DatePipe
  12. Formatting Dynamic Date Values
  13. DatePipe and Localization (Locale Support)
  14. Changing the Default Locale in Angular
  15. Example: Displaying Dates in Different Locales
  16. Handling UTC and Timezone Differences
  17. Common Format Tokens
  18. Using Safe Navigation with DatePipe
  19. Handling Null or Undefined Dates
  20. Applying DatePipe in Tables and Lists
  21. Real-World Example: Formatting API Dates
  22. Combining DatePipe with AsyncPipe
  23. Using DatePipe with Custom Components
  24. Performance Considerations
  25. Custom Pipes vs DatePipe
  26. Testing DatePipe in Unit Tests
  27. Best Practices for Using DatePipe
  28. Complete Example: Date Formatting Dashboard
  29. Summary
  30. 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:

FormatDescriptionExample Output
shortShort date/time9/9/25, 3:00 PM
mediumMedium date/timeOct 9, 2025, 3:00:00 PM
longLong date/timeOctober 9, 2025 at 3:00:00 PM GMT+5
fullFull date/timeThursday, October 9, 2025 at 3:00:00 PM GMT+05:00
shortDateShort date9/9/25
mediumDateMedium dateOct 9, 2025
longDateLong dateOctober 9, 2025
fullDateFull dateThursday, October 9, 2025
shortTimeShort time3:00 PM
mediumTimeMedium time3: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 format
  • HH = 24-hour format
  • a = 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: &lt;p&gt;{{ formattedDate }}&lt;/p&gt;,
  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

TokenDescriptionExample
yYear2025
yyTwo-digit year25
yyyyFull year2025
MMonth number9
MMTwo-digit month09
MMMAbbreviated monthOct
MMMMFull monthOctober
dDay9
ddTwo-digit day09
EEEEFull weekdayThursday
h / hhHour (12-hour)03
H / HHHour (24-hour)15
mmMinutes45
ssSeconds30
aAM/PMPM
zTimezoneGMT+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">
&lt;td&gt;{{ order.id }}&lt;/td&gt;
&lt;td&gt;{{ order.date | date:'shortDate' }}&lt;/td&gt;
&lt;td&gt;{{ order.total }}&lt;/td&gt;
</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 &lt; 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

  1. Always use ISO date strings for consistency.
  2. Use locale identifiers for internationalization.
  3. Avoid heavy formatting inside large loops for performance.
  4. Apply safe navigation for async or nullable data.
  5. Use DatePipe in services if the format is reused across components.
  6. Use custom pipes for relative time formatting.
  7. 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>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *