Angular 2 Date Pipe Example
On this page we will provide angular 2 Date Pipe example that formats a date according to locale rule. Angular 2 DatePipe provides different date formats that can be predefined date formats as well as custom date formats. DatePipe relates to CommonModule. The date input can be given as date object, milliseconds or an ISO date string. DatePipe is a Pipe API that works using pipe operator (|). On the left side of the pipe, we place date expression and on the right side we place required date formats. We will discuss DatePipe in detail here with examples using TypeScript.
Contents
Software Used
Pipe
DatePipe
Date Expression
Predefined Date Format
Custom Date Format
Complete Example using TypeScript
Run Application
References
Download Source Code
Software Used
Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0
Pipe
Pipe transforms the data into desired output for the given input. It works using pipe operator (|) as given below.
{{strDate | date :'short'}}
To the left side of the pipe operator, we place our input data and to the right side of the pipe operator we pass Pipe API that transforms the input into desired format. Pipecan also be chained. It means we can use more than one pipe operator together. The output of the first pipe will be input for second pipe and so on. Here we will discuss DatePipe API.
DatePipe
In angular 2 DatePipe is used as follows.
date_expression | date :'format' A. date_expression: The values of date expression are the followings.
1. Date object
2. Date in milliseconds as Number
3. An ISO String
B. date :'format' : Date format can be predefined values as well as custom values. We will discuss it in detail here.
Date Expression
Date expression can be date object declared as below.
objDate = Date.now(); We use DatePipe as follows with interpolation.
{{objDate | date :'short'}}
Output: 11/7/2016, 5:04 PM
Date expression can be in milliseconds.
numDate = 1478496544151; and we use it as below
{{numDate | date :'short'}}
Output: 11/7/2016, 10:59 AM
Date expression can also be an ISO string.
strDate = 'Mon Nov 07 2016 09:44:12 GMT+0530'; and we use it as follows.
{{strDate | date :'short'}}
Output: 11/7/2016, 9:44 AM
We can also use milliseconds and date string as date expression directly as follows.
{{1478496544151 | date :'short'}}
{{'Mon Nov 07 2016 09:44:12 GMT+0530'| date :'short'}}