This week, we covered basic date formatting with the date
pipe and the dateFormat
function. While those tools work perfectly well for most basic scenarios, there are times when we want to do more complex date manipulation, such as:
- Adding/subtracting days to a date
- Displaying a duration, such as: “Last update: 2 days ago“
- Comparing dates
Most people use Moment.js for such use cases, but Moment.js is now officially done and in maintenance mode.
One of the best alternatives available is date-fns. It uses modern Javascript and relies on the native Date object as much as possible. If you’ve used Moment.js in the past, date-fns
is going to look very familiar:
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
format(new Date(), "'Today is a' eeee")
//=> "Today is a Friday"
formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"
formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
Code language: JavaScript (javascript)
The library contains some interesting helper functions, such as closestTo
to get which date in an array is the closest to a given date, or formatDistanceToNow
, which returns meaningful, readable distances such as “less than a minute” or “about one month.”
These features are independent functions, which is excellent for Angular applications as it allows tree-shaking at build time (only the functions we need are included in our build output), compared to Moment, which had one single moment()
function that had everything in it, preventing proper tree-shaking.