Skip to main content

Angular Date Formatting

When building international applications, properly displaying dates according to each locale's conventions is critical for a good user experience. Angular provides powerful built-in tools for formatting dates that respect regional standards while giving developers flexible customization options.

Introduction to Angular Date Formatting

Date formatting in Angular is primarily handled through the DatePipe, which transforms date objects into readable strings based on locale-specific rules. This pipe is a key part of Angular's internationalization (i18n) system, allowing your application to display dates in formats familiar to users around the world.

The DatePipe can:

  • Format dates according to predefined patterns
  • Use locale-specific date formats (short, medium, long, full)
  • Create custom date formats using pattern strings
  • Adapt to the user's timezone

Basic Date Formatting with DatePipe

The most straightforward way to format dates in Angular is using the DatePipe in your templates.

Syntax

typescript
{{ dateValue | date[:format[:timezone[:locale]]] }}

Simple Examples

Here's how to use the DatePipe with various predefined formats:

html
<!-- Assuming dateValue = new Date(2023, 4, 15) (May 15, 2023) -->

<p>{{ dateValue | date }}</p>
<!-- Output: May 15, 2023 -->

<p>{{ dateValue | date:'short' }}</p>
<!-- Output: 5/15/23, 12:00 AM -->

<p>{{ dateValue | date:'medium' }}</p>
<!-- Output: May 15, 2023, 12:00:00 AM -->

<p>{{ dateValue | date:'long' }}</p>
<!-- Output: May 15, 2023 at 12:00:00 AM GMT+0 -->

<p>{{ dateValue | date:'full' }}</p>
<!-- Output: Monday, May 15, 2023 at 12:00:00 AM GMT+00:00 -->

Predefined Date Formats

Angular comes with several predefined format options that you can use as shortcuts:

NameExample Output
'short'5/15/23, 12:00 AM
'medium'May 15, 2023, 12:00:00 AM
'long'May 15, 2023 at 12:00:00 AM GMT+0
'full'Monday, May 15, 2023 at 12:00:00 AM GMT+00:00
'shortDate'5/15/23
'mediumDate'May 15, 2023
'longDate'May 15, 2023
'fullDate'Monday, May 15, 2023
'shortTime'12:00 AM
'mediumTime'12:00:00 AM
'longTime'12:00:00 AM GMT+0
'fullTime'12:00:00 AM GMT+00:00

Custom Date Formats

For more specific formatting needs, you can create custom patterns using the following format characters:

html
<!-- Custom format examples -->
<p>{{ dateValue | date:'yyyy-MM-dd' }}</p>
<!-- Output: 2023-05-15 -->

<p>{{ dateValue | date:'MMMM d, y, h:mm a' }}</p>
<!-- Output: May 15, 2023, 12:00 AM -->

<p>{{ dateValue | date:'EEEE, d MMMM y' }}</p>
<!-- Output: Monday, 15 May 2023 -->

Common Format Characters

CharacterDescriptionExample
yYear2023
MMonth1-12
MMMonth, leading zero01-12
MMMMonth, short nameJan-Dec
MMMMMonth, full nameJanuary-December
dDay of month1-31
ddDay of month, leading zero01-31
EDay of week, short nameSun-Sat
EEEEDay of week, full nameSunday-Saturday
hHour in 12-hour format1-12
hhHour in 12-hour format, leading zero01-12
HHour in 24-hour format0-23
HHHour in 24-hour format, leading zero00-23
mMinute0-59
mmMinute, leading zero00-59
sSecond0-59
ssSecond, leading zero00-59
aAM/PMAM/PM
ZTimezone-0700

Internationalization with Locales

The true power of Angular's date formatting comes into play when dealing with internationalization. You can display dates according to different locale conventions:

Setting Locale for the Entire Application

In your app module:

typescript
import { LOCALE_ID, NgModule } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeEs from '@angular/common/locales/es';

// Register the locales
registerLocaleData(localeFr);
registerLocaleData(localeEs);

@NgModule({
// ...
providers: [
{ provide: LOCALE_ID, useValue: 'en-US' } // Default locale
],
// ...
})
export class AppModule { }

Specifying Locale in Templates

You can override the application's default locale for specific date formatting:

html
<!-- Date in US English format -->
<p>{{ dateValue | date:'mediumDate':'UTC':'en-US' }}</p>
<!-- Output: May 15, 2023 -->

<!-- Date in French format -->
<p>{{ dateValue | date:'mediumDate':'UTC':'fr' }}</p>
<!-- Output: 15 mai 2023 -->

<!-- Date in Spanish format -->
<p>{{ dateValue | date:'mediumDate':'UTC':'es' }}</p>
<!-- Output: 15 de mayo de 2023 -->

Working with Timezones

Angular's DatePipe also supports timezone formatting:

html
<!-- Default timezone (browser's timezone) -->
<p>{{ dateValue | date:'medium' }}</p>

<!-- UTC timezone -->
<p>{{ dateValue | date:'medium':'UTC' }}</p>

<!-- Specific timezone -->
<p>{{ dateValue | date:'medium':'GMT+2' }}</p>

Programmatic Date Formatting

You can also use the DatePipe programmatically in your components:

typescript
import { DatePipe } from '@angular/common';

@Component({
selector: 'app-date-example',
template: `<p>Formatted date: {{ formattedDate }}</p>`,
providers: [DatePipe] // Provide DatePipe for injection
})
export class DateExampleComponent implements OnInit {
dateValue = new Date(2023, 4, 15);
formattedDate: string | null = null;

constructor(private datePipe: DatePipe) {}

ngOnInit() {
// Format the date programmatically
this.formattedDate = this.datePipe.transform(
this.dateValue,
'MMMM d, y',
'UTC',
'en-US'
);
// Output: "May 15, 2023"
}
}

Real-World Example: Multi-language Dashboard

Let's create a simple dashboard component that displays dates in the user's preferred language:

typescript
// user-dashboard.component.ts
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
selector: 'app-user-dashboard',
template: `
<div class="dashboard">
<h2>{{ 'Welcome to Your Dashboard' | translate }}</h2>

<div class="language-selector">
<button (click)="changeLanguage('en-US')">English</button>
<button (click)="changeLanguage('fr')">Français</button>
<button (click)="changeLanguage('es')">Español</button>
</div>

<div class="dashboard-card">
<h3>{{ 'Current Status' | translate }}</h3>
<p>{{ 'Last updated' | translate }}: {{ lastUpdated | date:'medium':'':currentLocale }}</p>
</div>

<div class="dashboard-card">
<h3>{{ 'Upcoming Events' | translate }}</h3>
<ul>
<li *ngFor="let event of events">
{{ event.name }} - {{ event.date | date:'fullDate':'':currentLocale }}
</li>
</ul>
</div>

<div class="dashboard-card">
<h3>{{ 'Report Generated' | translate }}</h3>
<p>{{ today | date:'EEEE, MMMM d, y, h:mm:ss a z':'':currentLocale }}</p>
</div>
</div>
`,
providers: [DatePipe]
})
export class UserDashboardComponent {
lastUpdated = new Date(2023, 4, 10, 15, 30);
today = new Date();
currentLocale = 'en-US';

events = [
{ name: 'Team Meeting', date: new Date(2023, 4, 20, 10, 0) },
{ name: 'Project Deadline', date: new Date(2023, 4, 25, 17, 0) },
{ name: 'Annual Conference', date: new Date(2023, 5, 15, 9, 0) }
];

changeLanguage(locale: string) {
this.currentLocale = locale;
// Additional code to update translations would go here
}
}

In this example, the user can switch between languages, and all date formats will automatically update to match the selected locale's conventions.

Best Practices for Date Formatting

  1. Always use the DatePipe rather than JavaScript's built-in date formatting to ensure proper internationalization.

  2. Consider user preferences by respecting their locale settings when displaying dates.

  3. Be consistent with date formats throughout your application.

  4. Use appropriate date format lengths based on context:

    • short for space-constrained areas
    • medium for general-purpose displays
    • long or full for detailed views
  5. Test with different locales to ensure your date displays properly across cultures.

  6. Remember timezone differences when displaying dates related to events or deadlines.

Summary

Angular's date formatting capabilities through the DatePipe provide a powerful and flexible way to display dates in your applications while respecting internationalization concerns. By understanding the different format options and how to apply locale-specific formatting, you can create applications that feel natural to users around the world.

Key takeaways:

  • Use the built-in DatePipe for all date formatting
  • Choose from predefined formats or create custom patterns
  • Register and use different locales to support international users
  • Consider timezones when displaying date information
  • Format dates programmatically when needed

Additional Resources

Exercises

  1. Create a date picker component that displays selected dates in formats appropriate for at least three different locales.

  2. Build a meeting scheduler that properly handles timezone differences between participants from different countries.

  3. Implement a "time ago" pipe that displays relative time (e.g., "5 minutes ago", "2 days ago") based on the user's locale.

  4. Create a calendar component that can switch between displaying dates in different formats (short, medium, long) based on user preference.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)