Language: JavaScript
Utility
date-fns was created to provide a functional, immutable, and tree-shakable alternative to libraries like Moment.js. Each function in date-fns is independent, allowing developers to import only what they need, resulting in smaller bundle sizes and better performance.
date-fns is a modern JavaScript library that provides comprehensive, lightweight, and modular functions for parsing, formatting, manipulating, and comparing dates.
npm install date-fnsyarn add date-fnsdate-fns provides over 200 functions for working with dates, including formatting, parsing, difference calculations, comparisons, adding or subtracting time, and more. Functions are pure and immutable, returning new date objects rather than modifying existing ones.
import { format } from 'date-fns';
const result = format(new Date(2025, 7, 22), 'yyyy-MM-dd');
console.log(result); // '2025-08-22'Formats a Date object to a string with the specified pattern.
import { parse } from 'date-fns';
const result = parse('2025-08-22', 'yyyy-MM-dd', new Date());
console.log(result);Parses a date string according to a given format into a Date object.
import { addDays, subMonths } from 'date-fns';
const today = new Date();
console.log(addDays(today, 5));
console.log(subMonths(today, 2));Demonstrates adding days or subtracting months from a date.
import { differenceInDays } from 'date-fns';
const start = new Date(2025, 7, 1);
const end = new Date(2025, 7, 22);
console.log(differenceInDays(end, start)); // 21Calculates the number of days between two dates.
import { isBefore, isAfter } from 'date-fns';
const d1 = new Date(2025, 7, 1);
const d2 = new Date(2025, 7, 22);
console.log(isBefore(d1, d2)); // true
console.log(isAfter(d2, d1)); // trueChecks if one date is before or after another.
import { startOfMonth, endOfMonth } from 'date-fns';
const today = new Date(2025, 7, 22);
console.log(startOfMonth(today));
console.log(endOfMonth(today));Gets the start and end dates of a month.
Import only the functions you need to reduce bundle size (tree-shaking).
Use pure functions to avoid mutating original Date objects.
Always provide a fallback Date for parsing when using `parse`.
Use UTC functions when working across time zones to avoid inconsistencies.
Combine with other date-fns utilities for cleaner and more readable date manipulations.