Sub topic 5
Formatting dates
This chapter assumes you can write a standalone Angular component, use interpolation ({{ }}) in its template, and pass parameters to a pipe with a colon, as in value | pipe:arg. It covers the built-in DatePipe, which turns a date value into display text. The date pipe is the one you will use most often. It also has the most pitfalls: time zones, token case, and input parsing.
What DatePipe accepts and returns
DatePipe is registered under the name date. It takes up to three parameters:
{{ value | date : format : timezone : locale }}formatis a predefined name or a pattern string. The default is'mediumDate'.timezoneis optional. If you omit it, the pipe uses the browser's local time zone.localeis optional. If you omit it, the pipe uses the application'sLOCALE_ID, which isen-USunless you change it.
The input can be one of three things:
- A
Dateobject. - A number, read as milliseconds since the Unix epoch.
- An ISO 8601 string, such as
'2024-01-15T14:05:09Z'.
The pipe handles bad input in two different ways:
null,undefinedand''producenull, so nothing is rendered.- Anything else that cannot be turned into a date throws a runtime error (
NG02300, "Invalid argument ... for pipe 'DatePipe'"). A string like'tomorrow'breaks rendering instead of showing blank text.
The pipe's job is to convert one date value into text through a fixed sequence of steps:
Predefined formats
Predefined format names are shortcuts. The pipe maps each name to a pattern for the current locale. The table shows the en-US patterns:
| Name | Pattern in `en-US` | Example output |
|---|---|---|
| `shortDate` | `M/d/yy` | 1/15/24 |
| `mediumDate` | `MMM d, y` | Jan 15, 2024 |
| `longDate` | `MMMM d, y` | January 15, 2024 |
| `fullDate` | `EEEE, MMMM d, y` | Monday, January 15, 2024 |
| `shortTime` | `h:mm a` | 2:05 PM |
| `short` | `M/d/yy, h:mm a` | 1/15/24, 2:05 PM |
| `medium` | `MMM d, y, h:mm:ss a` | Jan 15, 2024, 2:05:09 PM |
There are also mediumTime, longTime, fullTime, long and full. The long and full variants include the time zone name. The whitespace the pipe puts before PM can vary between Angular versions, because it comes from locale data. Don't compare the output of time formats with exact-string checks unless you pin the version.
Predefined names are the better default, because they adapt when the locale changes. A German user sees 15.01.24 for shortDate without any change to your template.
Custom patterns
When no predefined name fits, pass a pattern built from tokens. The most useful tokens are:
| Token | Meaning | Example |
|---|---|---|
| `y`, `yy`, `yyyy` | Year: numeric, two-digit, four-digit | 2024, 24, 2024 |
| `M`, `MM`, `MMM`, `MMMM` | Month: number, padded, abbreviated, full name | 1, 01, Jan, January |
| `d`, `dd` | Day of month | 5, 05 |
| `E`, `EEEE` | Weekday: abbreviated, full | Mon, Monday |
| `H`, `HH` | Hour, 24-hour clock | 14 |
| `h`, `hh` | Hour, 12-hour clock | 2 |
| `m`, `mm` | Minute | 5, 05 |
| `s`, `ss` | Second | 9, 09 |
| `a` | AM/PM marker | PM |
| `z`, `Z` | Time zone name, offset | GMT, +0000 |
Text that should appear literally goes inside single quotes:
<p>{{ createdAt | date : "EEEE, d 'of' MMMM" }}</p>
<p>{{ createdAt | date : 'yyyy-MM-dd HH:mm' }}</p>Use a double-quoted string when the pattern contains single quotes, as in the first line.
Token mistakes that look correct
Three mistakes pass code review because the output looks plausible:
mmversusMM.MMis the month andmmis the minute.yyyy-mm-ddprints the minute in the month position.YYYYversusyyyy.YYYYis the week-numbering year. Around New Year the two differ: 31 December 2024 is in week 1 of 2025, soYYYYprints2025. Useyyyyunless you really want ISO week years.hhwithouta. A 12-hour clock with no AM/PM marker is ambiguous. Pairhorhhwitha, or useHorHH.
Time zones
A Date holds one instant in time. The pipe decides which wall-clock time to show for it. With no timezone argument it uses the browser's zone, so two users looking at the same instant can see different dates.
The timezone parameter accepts these values:
'UTC'or'GMT'.- An offset such as
'+0200'or'-0500'.
It does not accept IANA names such as 'Europe/Berlin'. Angular does not look up daylight-saving rules for named zones, so an offset is fixed, and you have to adjust it yourself when daylight saving changes.
import { DatePipe } from '@angular/common';
import { Component } from '@angular/core';
@Component({
selector: 'app-event-times',
standalone: true,
imports: [DatePipe],
template: `
<p>Local: {{ startsAt | date : 'yyyy-MM-dd HH:mm' }}</p>
<p>UTC: {{ startsAt | date : 'yyyy-MM-dd HH:mm' : 'UTC' }}</p>
<p>UTC+2: {{ startsAt | date : 'yyyy-MM-dd HH:mm' : '+0200' }}</p>
`,
})
export class EventTimesComponent {
startsAt = new Date('2024-01-15T23:30:00Z');
}The UTC line always shows 2024-01-15 23:30. The +0200 line shows 2024-01-16 01:30, which is the next calendar day. The local line depends on where the browser runs. If the same instant must show the same date for everyone, such as an event deadline, pass a fixed zone.
Date-only strings
The JavaScript Date constructor reads '2024-01-15' as midnight UTC. DatePipe reads a date-only string as midnight in local time. For a birthday or invoice date, this is the behavior you want, because the pipe shows Jan 15, 2024 in every time zone.
The risk is mixing the two. If you build the value with new Date('2024-01-15') and then format it, a user west of UTC sees Jan 14, 2024. Pass the original string to the pipe, or format with 'UTC'.
Changing the defaults for the whole app
If every date in the application should use the same format or zone, set both once with the DATE_PIPE_DEFAULT_OPTIONS token instead of repeating parameters:
import { DATE_PIPE_DEFAULT_OPTIONS } from '@angular/common';
import { ApplicationConfig } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [
{
provide: DATE_PIPE_DEFAULT_OPTIONS,
useValue: { dateFormat: 'shortDate', timezone: 'UTC' },
},
],
};After this, {{ createdAt | date }} uses shortDate in UTC. An explicit parameter in a template still overrides the default. Note that the default dateFormat applies only when the template gives no format. A global UTC zone is a deliberate choice, so confirm it matches how your backend stores times.
Formatting a different locale on one value
The third parameter changes the locale for a single use. A non-default locale must be registered first, or the pipe throws an error saying locale data is missing. The previous chapter's locale section covers registration; the pattern looks like this:
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);Then the template can use {{ createdAt | date : 'fullDate' : undefined : 'fr' }}. To keep the default time zone while setting the locale, pass undefined as the second parameter, as shown. Predefined names and month and weekday tokens produce French text. Numeric tokens keep their position, so 'dd/MM/yyyy' produces the same layout in every locale.
Pure pipe behavior
DatePipe is a pure pipe. Angular re-runs it only when the input reference or a parameter changes. If you mutate a Date in place, nothing updates:
this.deadline.setDate(this.deadline.getDate() + 1); // template still shows the old date
this.deadline = new Date(this.deadline.getTime() + 86_400_000); // new reference, template updatesAlways assign a new Date object when the value changes. With signals, deadline.set(new Date(...)) does the same thing. Avoid new Date() inside the template or in a getter. A getter that returns a new object on every call defeats the pure pipe's check and forces reformatting on each change detection run.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| Console error `NG02300` | The value is not a date, for example a free-text string | Validate or parse before the template, or guard with `@if` |
| Month shows as minutes | `mm` used for the month | Use `MM` |
| Year is wrong in late December | `YYYY` used | Use `yyyy` |
| Date is one day early for some users | A UTC date was shown in local time | Pass `'UTC'`, or keep the raw date-only string |
| Output stays unchanged after editing a `Date` | The pipe is pure and the reference did not change | Assign a new `Date` |
| Error about missing locale data | Locale not registered | Call `registerLocaleData` for that locale |
Exercise
An API returns the string '2024-12-31'. A template shows it with {{ day | date : 'YYYY-MM-dd' }}. What does it print for an en-US user in any time zone, and what two changes make it correct?
Show answer
It prints 2025-12-31 for the week-year part. 31 December 2024 falls in week 1 of 2025, so YYYY gives 2025 while the month and day stay 12-31. Change YYYY to yyyy to get 2024-12-31. Keep passing the original date-only string, because the pipe reads it as local midnight, so the day does not move between zones. Converting it first with new Date('2024-12-31') would read it as UTC midnight and show 12-30 to users west of UTC.
Exercise
A Date holds the instant 2024-03-10T02:30:00Z. Write the template expression that shows it as 2024-03-09 21:30 regardless of the browser's time zone, and say why 'America/New_York' is not a suitable value for the time zone parameter.
Show answer
{{ when | date : 'yyyy-MM-dd HH:mm' : '-0500' }}. The offset -0500 moves 02:30 UTC back five hours to 21:30 on 9 March. The pipe accepts only UTC, GMT or a numeric offset, not IANA zone names, so 'America/New_York' is not valid, and a fixed offset also would not follow daylight-saving changes.