In this post we will learn how to use date-fns in Angular application. But first let’s understand date-fns.
date-fns is a date utility library which provides simple and extensive set of functions to manipulate JavaScript dates.
For example, say we want to present to user a particular date-time based on a time-zone instead of a date based on the system / browser time-zone (typically working with UTC is easy), this is actually difficult to do until unless you are using some library which parses dates into time-zones. date-fns provides nice set of functions to achieve this.
utcToZonedTime(new Date('2018-09-01T16:01:36.386Z'), 'America/Chicago')
Above function parses the UTC date into a date with the specified time-zone, i.e representing a local time in that time-zone.
Now, let’s get stated with the Angular project.
Steps:
- Create the angular app.
- Add the project dependencies, like, date-fns.
- Use the library functions from date-fns.
- Create a simple pipe service for date-fns to format dates in the template.
Create the angular app
We are going to use the angular guide to create a new angular project.
ng new ng-date-fns
Now we have our angular application ready, let’s try to add the dependencies.
Add the dependencies
npm i bootstrap date-fns --save
Here we are installing few packages, bootstrap (To display the data in a table) and date-fns (JavaScript date utility library).
Using the library
// Library is tree-shakable, import only what is needed.
import format from 'date-fns/format';
format(new Date(), 'MM/dd/yyyy');
Here, one advantage of using date-fns is its tree-shakable, we can just import only what is needed, which compiles to less bundle size!.
Pipe service
import { Pipe, PipeTransform } from '@angular/core';
import format from 'date-fns-tz/format';
import utcToZonedTime from 'date-fns-tz/utcToZonedTime';
@Pipe({
name: 'datefns'
})
export class DateFnsPipe implements PipeTransform {
transform(value: any, timeZone: string, pattern: string, defaultText: string = "Invalid date!") {
if (!value) {
return defaultText;
}
if (timeZone) {
const zonedDate = utcToZonedTime(value, timeZone);
return format(zonedDate, pattern, { timeZone });
}
return format(value, pattern);
}
}
// Use the pipe in the template
<td>{{ utcDate | datefns:'Europe/Berlin':'MMM dd yyyy, hh:mm aa' }}</td>
**You would also need to declare the pipe in the module.
I guess thats it…we have started to use the date-fns in Angular project.
Checkout complete code at Github. And don’t forget to like or share, you can also leave a comment!!, thanks.