date-fns

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.

Installation

npm: npm install date-fns
yarn: yarn add date-fns

Usage

date-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.

Formatting a date

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.

Parsing a date string

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.

Adding and subtracting time

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.

Difference between dates

import { differenceInDays } from 'date-fns';
const start = new Date(2025, 7, 1);
const end = new Date(2025, 7, 22);
console.log(differenceInDays(end, start)); // 21

Calculates the number of days between two dates.

Comparing 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)); // true

Checks if one date is before or after another.

Start and end of time units

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.

Error Handling

Invalid Date: Ensure the input is a valid Date object or properly formatted string. Use `isValid(date)` to check before processing.
Parsing errors: Ensure the string matches the format exactly when using `parse()`.

Best Practices

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.