Estimated read time: 3 minutes   | 1 comments

Use Angular DatePipe Programmatically

Use Angular DatePipe Programmatically

Last updated: April 22, 2021 6:47AM

This will be a quick article on how take advantage of the Angular DatePipe inside your TypeScript code. Everyone knows how to use it inside templates, but not many know how easy and useful it is to also use it programmatically.

Normal Use in Templates

The Angular DatePipe is a very useful and commonly used pipe in the component templates of Angular projects. Here is how it is most commonly used:

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p>
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

Use Programmatically in Code

Now let's see the less commonly known way of using the DatePipe inside our TypeScript code.

// Import the DatePipe.
import { DatePipe } from '@angular/common';

/**
 * Takes a date and transforms it into a string based on the given date format.
 * Utilizes the Angular `DatePipe` internally.
 * @param date The date string, number of `Date` object to transform.
 * @param format A predefined Angular `DatePipe` format or a custom date format
 * string.
 * @returns The transformed date as a string.
 */
const formatDate = (date: string | number | Date, format: string): string {
  // Create an instance of the pipe.
  const datePipe = new DatePipe('en-US');
  // Call the transform method of the pipe object.
  return datePipe.transform(params.value, format);
}

// Call our new function:
console.log(formatDate(new Date(), 'short'));
// Outputs: 6/15/15, 9:03 AM

So, the first step is importing the DatePipe from @angular/common. Then we instantiate a DatePipe object. Notice we must pass a locale to the DatePipe constructor. We will pass in en-US because that is the only locale data comes with Angular. To localize dates in another language, you must import the corresponding locale data.

Now that we have instantiated an instance of the DatePipe, all we need to do to convert a date is call the transform() function.

The transform() Function of Angular Pipes

You don't need to know this, but here is a quick explanation on how the transform() function works with Angular pipes. The transform() function is common to all Angular pipes. This is what actually gets called when you use the template pipe syntax variable | date. If you ever create your own pipe, you will create a class that implements the PipeTransform interface which has the transform() function you need to implement. An interface that is implemented by pipes in order to perform a transformation. Angular invokes the transform method with the value of a binding as the first argument, and any parameters as the second argument in list form.

Using the DatePipe transform() Function

We then pass in two parameters to the transform() function:

  1. The first is the date that we want to convert, which is in the form of a string, number, or JavaScript Date object.

  2. The second is the date format string that we want the outputted date string to be. This can be one of the predefined Angular DatePipe formats like, 'short', 'fullDate', or 'mediumTime'. Or you can provide a custom date format string like 'M/d/yy, h:mm a'. See the Angular docs for all the possible date format strings.

Examples

Now let's try calling our new formatDate() function.

console.log(formatDate(new Date(), 'EEE M/d/yy, h:mm a'));
// Outputs: Tue 9/15/21, 9:03 AM

// Or use on of the Angular DatePipe's predefined formats.
console.log(formatDate(new Date(), 'short'));
// Outputs: 6/15/15, 9:03 AM

// You can pass a string, number, or Date() object as the date. As a number:
console.log(formatDate(1619084721684, 'short'));
// Outputs: 6/15/15, 9:03 AM

// Pass a string:
console.log(formatDate('2021-04-22T09:47:23.119Z', 'short'));
// Outputs: 6/15/15, 9:03 AM

As you can see, we are using our function that utilizes the DatePipe outside of an Angular template! We can call this function anywhere and get all the same functionality as if we were using the pipe syntax in a template. Remember that we can transform not only JavaScript Date objects, but also a number representing a Unix Timestamp like, 1619087019, or a string ISO Timestamp like, 2021-04-22T09:47:23.119Z.

Summary

So here we learned how to use the Angular DatePipe outside of a component template, and without the pipe syntax. We gained access to all the great date format parsing capabilities of Angular's DatePipe anywhere in our code! This helps prevent having to learn and import yet another JavaScript library into our project. We also touched on how Angular pipes work in general, by implementing the PipeTransform interface and its transform() function. And also, that the Angular pipe syntax actually calls the transform() function.

Thanks for reading and I hope you learned something. If you have any questions or comments, please post in the comment section below!

Leave a Comment 1 comments

Preview rendered markdown comment...
CoderBoi99 October 20, 2022 5:46 AM 1 year ago

Nice article, thanks! 😀👍️