DatePipe with example in Angular

The Angular DatePipe is a built-in pipe used to format dates according to specific patterns and locales. Here's an explanation with examples:

How to use the DatePipe:

Import: Import the DatePipe from the @angular/common module in your component.

TypeScript

import { Component } from '@angular/core';

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

Use code with caution.

Inject: Inject the DatePipe into your component constructor.

TypeScript

@Component({

})

export class MyComponent {

  constructor(private datePipe: DatePipe) {}

}

Use in Template: Use the pipe in your component's template with the following syntax:

HTML

{{ yourDate | date: 'format' }}


yourDate: The date value you want to format (can be a Date object, timestamp, or ISO date string).

format: The desired format string or a pre-defined format from the DatePipe.

Pre-defined Formats:

'short': Similar to 'mediumDate' but includes time (e.g., "M/d/yy, h:mm a")

'medium': Includes month, day, year, and time (e.g., "MMM d, y, h:mm:ss a")

'long': Includes month name, day, year, time, and timezone (e.g., "MMMM d, y, h:mm:ss a z")

'full': Similar to 'long' but includes weekday (e.g., "EEEE, MMMM d, y, h:mm:ss a zzzz")

'shortDate': Month, day, and year (e.g., "M/d/yy")

'mediumDate': Month name and year (e.g., "MMM d, y")

'longDate': Full month name and year (e.g., "MMMM d, y")

'fullDate': Weekday, full month name, and year (e.g., "EEEE, MMMM d, y")


Custom Formats:

You can also create custom formats using placeholders like:


'y': Year (e.g., "yyyy" for full year, "yy" for abbreviated)

'M': Month (e.g., "MM" for zero-padded, "M" for non-padded)

'd': Day (e.g., "dd" for zero-padded, "d" for non-padded)

'h': Hour (1-12 format)

'H': Hour (24-hour format)

'm': Minutes (zero-padded)

's': Seconds (zero-padded)

'a': AM/PM indicator

'z': Timezone offset

'zzzz': Full timezone name

Examples:


HTML

{{ today | date: 'mediumDate' }}

{{ eventTime | date: 'h:mm a' }}

{{ birthday | date: 'yyyy-MM-dd' }}

Remember to adapt the format string to your specific needs. For a complete list of formats and customization options, refer to the official Angular documentation: https://angular.io/api/common/DatePipe




DatePipe with example in Angular
DatePipe with example in Angular


Post a Comment

0 Comments