Tel Map

Blog

Angular2 Date Pipe

In Angular2 you can use “pipes” (in earlier versions called “filters”) to adjust data bindings to given situations. Then name comes from the “pipe symbol” (|) that is also known from Unix/Linux command shells to manipulate data streams. In Angular 2, the most common pipes are “date” (date format rendering), “async” (asynchronous data binding of Observables) and String-manipulating pipes like “uppercase” / “lowercase”. I will focus on the “date” pipe in this article.

How do pipes work

Basically, they take data from a binding of the component and return another value, given by a mapping function. To use them in an expression, just write the data exporession, then the pipe symbol, then then name of the pipe, e.g.

The date pipe

In the case of the “date” pipe, imagine you have a property of your component that is of type Date:

Now what happens, if you just print the date out in the template:

The result will look something like this: “Date Example: Sun Mar 27 2016 15:00:31 GMT+0200”. Doesn’t look so nice, does it?

Now what we want is a proper date formatter. This is what the date pipe is for:

And now it will print like this: “Date Example: Mar 27, 2016”.

Configuring the pipe

But wait, what if we don’t only want to display the date, but also the time? Fortunately, pipes also can be given parameters, in the case of the date pipe, the date format to use. So to display the correct date and time, we can pass the date format appended by a colon:

Parameters after the colon are then added as parameters to the pipe class. The result will look like this: “Mar 27, 2016, 3:00:31 PM”

2016-06-13 |
Tags: , ,

Leave a Reply

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