Course contentsShow
← Web Development
Lesson 2738 of 2,98249. Dates, Times, and Numbers on the WebFree lesson

date-fns: Arithmetic and Manipulation

Adding, subtracting, and manipulating dates with addDays, subMonths, startOfWeek, and similar functions.

date-fns: Arithmetic and Manipulation

You'll learn how to perform date calculations using date-fns's intuitive arithmetic and manipulation functions.

The Core Idea

Date arithmetic involves adding or subtracting time intervals (days, months, years) and manipulating dates to find boundaries like the start of a week or end of a month. While native JavaScript's Date object requires manual millisecond math and mutation, date-fns provides immutable, readable functions that handle these operations cleanly—including tricky edge cases like month-end rollovers and leap years.

Think of date-fns functions as building blocks: instead of manually calculating "90 days from now," you simply ask addDays(today, 90).

Common Arithmetic Functions

Adding time:

import { addDays, addMonths, addYears } from 'date-fns';

const today = new Date(2024, 0, 15); // Jan 15, 2024
const inTenDays = addDays(today, 10);     // Jan 25, 2024
const nextMonth = addMonths(today, 1);    // Feb 15, 2024
const nextYear = addYears(today, 1);      // Jan 15, 2025

Subtracting time:

import { subDays, subMonths } from 'date-fns';

const yesterday = subDays(today, 1);      // Jan 14, 2024
const lastMonth = subMonths(today, 1);    // Dec 15, 2023

Manipulation to Boundaries

Find the start or end of time periods:

import { startOfWeek, endOfMonth, startOfYear } from 'date-fns';

const weekStart = startOfWeek(today);     // Sunday of current week
const monthEnd = endOfMonth(today);       // Jan 31, 2024
const yearStart = startOfYear(today);     // Jan 1, 2024

These functions return new Date objects, preserving immutability. They handle edge cases automatically—adding months to Jan 31 correctly gives you the last day of February, not an invalid date.

Key Takeaway: date-fns arithmetic functions (addDays, subMonths) and manipulation functions (startOfWeek, endOfMonth) provide immutable, reliable date calculations without manual millisecond math or mutation pitfalls.