date-fns: Philosophy and Installation
What you'll learn: How date-fns takes a functional, modular approach to date manipulation and how to add it to your project.
The Philosophy Behind date-fns
After understanding the pitfalls of the native Date object, you need a library that solves those problems without bloating your bundle. date-fns treats dates as immutable and provides pure functions that always return new values instead of mutating existing dates.
Think of date-fns like a toolbox where you only grab the specific tools you need, rather than carrying the entire workshop. Each function is a separate ES module—addDays, format, differenceInHours—so modern bundlers can tree-shake away anything you don't import. This contrasts with older libraries where you'd import the entire API even if you only needed one method.
The library embraces functional programming principles: functions don't have side effects, they accept the date as the first argument (making them easy to compose), and they work with plain JavaScript Date objects rather than creating wrapper classes.
Installing date-fns
For modern JavaScript projects with npm or yarn:
npm install date-fns
Or with Yarn:
yarn add date-fns
Then import only what you need:
import { format, addDays } from 'date-fns';
const today = new Date();
const nextWeek = addDays(today, 7); // today unchanged
const formatted = format(nextWeek, 'yyyy-MM-dd');
Notice how today remains unchanged—date-fns returns a new date. This immutability prevents the mutation bugs we saw with native Date methods.
Key Takeaway: date-fns provides tree-shakable, immutable date functions that work with native Date objects, keeping your bundle small while solving JavaScript's date handling problems through functional design.