How to Easily Add and Subtract Dates in JavaScript β€” date-fns is a solid choice

Dev By RayRayDev By RayRay
11 min read

Are you seeking a straightforward solution to manipulate dates in JavaScript? Do you need to effortlessly add or subtract time units such as seconds, minutes, days, weeks, months, or years?

You're in the right place! Learn how to add and subtract dates easily in JavaScript using date-fns. Our guide helps you understand these steps in a simple way, making your code work better and faster. Start improving your date skills in JavaScript with us now!

divider-byrayray.png

The Benefits of Choosing date-fns

If you've been in the JavaScript world for a while, you're likely familiar with MomentJS, once the go-to library for JavaScript date calculations, timezones, and formatting. However, as we started focusing more on efficient application performance, MomentJS's inability to tree-shaking and its impact on bundle size became an issue.

This led to the rise of modular JavaScript date libraries, among which date-fns emerged as a leading choice. Here's why: If you're mindful about not bloating your application bundle, date-fns is a sound choice. Its modular design allows you to include only the needed functions, reducing the impact on your bundle size and enhancing application performance.

And maybe even more valuable, date-fns is completely open source πŸ’ͺ.

But let's get started where you came for the practical examples to help you further do Date calculations in JavaScript efficiently.

divider-byrayray.png

TLDR;

For those who don't want to read the whole article, here is the TLDR on how to do Date calculations with date-fn's.

Add days, weeks, months, and years to Date

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

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date); // Tue Jan 31 2023
console.log('Add 2 days: ', addDays(date, 2)); // Thu Feb 02 2023
console.log('Add 5 weeks: ', addWeeks(date, 5)); // Tue Mar 07 2023
console.log('Add 3 months: ', addMonths(date, 3)); // Sun Apr 30 2023
console.log('Add 8 years: ', addYears(date, 8)); // Fri Jan 31 2031
console.log('Add 5 days, 2 months, 3 weeks and 7 years: ', add(date, {
    days: 5,
    weeks: 3,
    months: 2,
    years: 7
})); // Fri Apr 26 2030
console.log(date); // Tue Jan 31 2023

Subtract days, weeks, months, years to Date

import { sub, subDays, subWeeks, subMonths, subYears } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date); // Tue Jan 31 2023
console.log('Subtract 2 days: ', subDays(date, 2)); // Sun Jan 29 2023
console.log('Subtract 5 weeks: ', subWeeks(date, 5)); // Tue Dec 27 2022
console.log('Subtract 3 months: ', subMonths(date, 3)); // Mon Oct 31 2022
console.log('Subtract 8 years: ', subYears(date, 8)); // Sat Jan 31 2015
console.log('Subtract 5 days, 2 months, 3 weeks and 7 years: ', sub(date, {
    days: 5,
    weeks: 3,
    months: 2,
    years: 7
})); // Wed Nov 04 2015
console.log(date); // Tue Jan 31 2023

divider-byrayray.png

Installation

Before using date-fns in your code, you need to install it.

npm install date-fns --save
# or
yarn add date-fns

After installation, you can choose to import the modules in different ways.

// ESM
import { addDays, subDays } from 'date-fns';
// ES 2015
import addDays from 'date-fns/addDays';
import subDays from 'date-fns/subDays';
// CommonJS
const addDays = require('date-fns/addDays');
const subDays = require('date-fns/subDays');

divider-byrayray.png

How To Add Days to a Date

Let's start with something simple. Add one or more days to a date.

import { addDays } from 'date-fns'

// 4th of July 2023
const date = new Date(2023, 6, 4);

console.dir(date); // Tue Jul 04 2023
console.log('Add 3 days: ', addDays(date, 3)); // Fri Jul 07 2023
console.log('Add 7 days: ', addDays(date, 7)); // Tue Jul 11 2023
console.log('Add 31 days: ', addDays(date, 31)); // Fri Aug 04 2023
console.log(date); // Tue Jul 04 2023

Check it on runkit.

First, we have imported the addDays from date-fn's. We created a variable with a date and added 3, 7, and 31 days.

Each util function in date-fns will return a new Date object. This is nice, so you can continue to add more calculations on top of it. Also, notice that these functions don't change the date in the variable date, so all the functions are pure JavaScript functions.

Let's continue with subtracting days from a date.

divider-byrayray.png

How To Subtract Days from a Date

Subtracting days is equally simple, like the previous example.

import { subDays } from 'date-fns'

// 4th of July 2023
const date = new Date(2023, 6, 4);

console.log(date); // Tue Jul 04 2023
console.log('Subtract 3 days: ', subDays(date, 3)); // Sat Jul 01 2023
console.log('Subtract 7 days: ', subDays(date, 7)); // Tue Jun 27 2023
console.log('Subtract 31 days: ', subDays(date, 31)); // Sat Jun 03 2023
console.log(date); // Tue Jul 04 2023

Check it on runkit.

Well, what more can I say? Like, it's that easy, right πŸ˜…. Let's continue with adding months to a JavaScript Date.

divider-byrayray.png

How To Add Weeks to a Date

Adding weeks to a Date is also a very common thing to do in, for example, booking systems. Well, date-fns is also supporting that.

import { addWeeks } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date); // Tue Jan 31 2023
console.log('Add 1 week: ', addWeeks(date, 1)); // Tue Feb 07 2023
console.log('Add 3 weeks: ', addWeeks(date, 3)); // Tue Feb 21 2023
console.log('Add 9 weeks: ', addWeeks(date, 9)); // Tue Apr 04 2023
console.log('Subtract 52 weeks: ', subWeeks(date, 52)); // Tue Feb 01 2022

Check it on runkit.

divider-byrayray.png

How To Subtract Weeks from a Date

Well, subtracting weeks is as simple as adding weeks with date-fn's.

import { subWeeks } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date); // Tue Jan 31 2023
console.log('Subtract 1 week: ', subWeeks(date, 1));// Tue Jan 24 2023
console.log('Subtract 3 weeks: ', subWeeks(date, 3)); // Tue Jan 10 2023
console.log('Subtract 9 weeks: ', subWeeks(date, 9)); // Tue Nov 29 2022

Check it on runkit.

divider-byrayray.png

How To Add Months to a Date

Adding months to a JavaScript Date can be simple, but in some cases, it can be tricky.

import { addMonths } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date); // Tue Jan 31 2023
console.log('Add 1 month: ', addMonths(date, 1)); // Tue Feb 28 2023
console.log('Add 3 months: ', addMonths(date, 3)); // Sun Apr 30 2023
console.log('Add 9 months: ', addMonths(date, 9)); // Tue Oct 31 2023
console.log(date); // Tue Jan 31 2023

Check it on runkit.

Let's say it's the 31st of January 2023, but we want to add one month. Well, you need to know how many days there are next month. This is tricky because that differs during leap years. So that's why in 2023, it will be the 28th of February, but if you try to add one month to the 31st of January in 2024, the outcome will be the 29th of February.

import { addMonths } from 'date-fns'

//31st of January 2024
const date = new Date(2024, 0, 31);

console.log(date); // Wed Jan 31 2024
console.log('Add 1 month: ', addMonths(date, 1)); // Thu Feb 29 2024

Check it on runkit.

So this already proves why date-fns is much easier to use than plain JavaScript Date.

divider-byrayray.png

How To Subtract Months from a Date

Like adding months to a Date , subtracting months from a Date is equally simple.

import { subMonths } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date); // Tue Jan 31 2023
console.log('Subtract 1 month: ', subMonths(date, 1)); // Sat Dec 31 2022
console.log('Subtract 3 months: ', subMonths(date, 3)); // Mon Oct 31 2022
console.log('Subtract 9 months: ', subMonths(date, 9)); // Sat Apr 30 2022
console.log(date); // Tue Jan 31 2023

Check it on runkit.

divider-byrayray.png

How To Add Years to a Date

Adding years is a perfect example of how date-fns handles cases with leap years.

import { addYear } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);
const leapYear = new Date(2024, 1, 29);

console.log(date);
console.log('Add 1 year: ', addYears(date, 1));
console.log('Add 1 year to leap year: ', addYears(leapYear, 1));
console.log('Add 3 year: ', addYears(date, 3));
console.log('Add 9 year: ', addYears(date, 9));
console.log(date);

Check it on runkit.

In the example, you can see that every outcome of the addYears function is correct. The case with the leap year is also perfect.

divider-byrayray.png

How To Subtract Years from a Date

In this example, you can also see that subtracting years from a Date is a breeze with date-fn's.

import { subYears } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);
const leapYear = new Date(2024, 1, 29);

console.log(date); // Tue Jan 31 2023
console.log('Subtract 1 year: ', subYears(date, 1)); // Mon Jan 31 2022
console.log('Subtract 1 year to leap year: ', subYears(leapYear, 1)); // Tue Feb 28 2023
console.log('Subtract 3 year: ', subYears(date, 3)); // Fri Jan 31 2020
console.log('Subtract 9 year: ', subYears(date, 9)); // Fri Jan 31 2014
console.log(date); // Tue Jan 31 2023

Check it on runkit.

divider-byrayray.png

How To Add or Subtract Hours, Minutes, or Seconds from a Date

Equally important in calculating Date in JavaScript is time because adding 2 hours when it's 22:30 is not the same day but is the next day. Or it calculates a flight time traveling through different time zones. It's not easy, but lucky you can use date-fns for it.

import { 
    addSeconds, subSeconds, addMinutes, 
    subMinutes, addHours, subHours
} from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31, 10, 18, 35);

console.log(date); // Tue Jan 31 2023 10:18:35
console.log('Add 15 seconds: ', addSeconds(date, 15)); // Tue Jan 31 2023 10:18:50
console.log('Subtract 2 seconds: ', subSeconds(date, 2)); // Tue Jan 31 2023 10:18:33
console.log('Add 15 minutes: ', addMinutes(date, 15)); // Tue Jan 31 2023 10:33:35
console.log('Subtract 2 minutes: ', subMinutes(date, 2)); // Tue Jan 31 2023 10:16:35
console.log('Add 15 hours: ', addHours(date, 15)); // Wed Feb 01 2023 01:18:35
console.log('Subtract 2 hours: ', subHours(date, 2)); // Tue Jan 31 2023 08:18:35

Check it on runkit.

divider-byrayray.png

How To Add or Subtract Days, Weeks, Months, and Years to a Date

Let's say we want to add seven days, three weeks, and nine months to date; we can combine the addDays, addWeeks, and addMonths for that. But even faster is the add or sub function in which you only have to add a parameter in which you configure it.

import { add, sub } from 'date-fns'

//31st of January 2023
const date = new Date(2023, 0, 31);

console.log(date);
console.log('Subtract 5 days, 2 months, 3 weeks and 7 years: ', sub(date, {
    days: 5,
    weeks: 3,
    months: 2,
    years: 7
})); // Wed Nov 04 2015
console.log('Add 5 days, 2 months, 3 weeks and 7 years: ', add(date, {
    days: 5,
    weeks: 3,
    months: 2,
    years: 7
})); // Fri Apr 26 2030

Check it on runkit.

divider-byrayray.png

How To Calculate the Difference Between Dates

In many situations, we want to calculate the difference between two dates. There are many functions in date-fns to do that easily.

import { 
    differenceInSeconds, differenceInMinutes, differenceInHours, 
    differenceInDays, differenceInCalendarDays, differenceInBusinessDays, 
    differenceInWeeks, differenceInCalendarWeeks, differenceInMonths, 
    differenceInCalendarMonths, differenceInQuarters, differenceInCalendarQuarters, 
    differenceInYears, differenceInCalendarYears 
} from 'date-fns'

//31st of January 2023
const fromDate = new Date(2023, 0, 31);
const toDate = new Date(2025, 7, 15);
const log = console.log

log(`Diff in seconds: ${differenceInSeconds(toDate, fromDate)}`) // 80089200
log(`Diff in minutes: ${differenceInMinutes(toDate, fromDate)}`) // 1334820
log(`Diff in hours: ${differenceInHours(toDate, fromDate)}`) // 22247

log(`Diff in days: ${differenceInDays(toDate, fromDate)}`) // 927
log(`Diff in business days: ${differenceInBusinessDays(toDate, fromDate)}`) // 663
log(`Diff in calendar days: ${differenceInCalendarDays(toDate, fromDate)}`) // 927

log(`Diff in weeks: ${differenceInWeeks(toDate, fromDate)}`) // 132
log(`Diff in calendar weeks: ${differenceInCalendarWeeks(toDate, fromDate)}`) // 132

log(`Diff in months: ${differenceInMonths(toDate, fromDate)}`) // 30
log(`Diff in calendar months: ${differenceInCalendarMonths(toDate, fromDate)}`) // 31

log(`Diff in quarters: ${differenceInQuarters(toDate, fromDate)}`) // 10
log(`Diff in calendar quarters: ${differenceInCalendarQuarters(toDate, fromDate)}`) // 10

log(`Diff in years: ${differenceInYears(toDate, fromDate)}`) // 2
log(`Diff in calendar years: ${differenceInCalendarYears(toDate, fromDate)}`) // 2

Check it on runkit.

In the example, we have calculated the differences between the two dates. Seconds, minutes, hours, days, weeks, months, quarters, and years.

If you check the days, you see three different functions. Days, business days, and calendar days are slightly different from each other:

  • differenceInDays calculates full-day periods between two dates.
  • differenceInBusinessDays calculates only business days and ignores the weekends.
  • differenceInCalendarDays calculates the difference between two dates but ignores the time.

You have two functions for the weeks, months, quarters, and years. The method with Calendar in it ignores the time part; the other one considers the time. (check the documentation if you want to dive deeper into it)

divider-byrayray.png

Conclusion

Navigating through date calculations in JavaScript might initially seem like a complex labyrinth. However, as we've explored throughout this guide, it doesn't have to be. With the right tools and understanding, adding and subtracting dates – seconds, minutes, hours, days, weeks, months, or even years – can be effortless.

By choosing a powerful and modular library like date-fans, you're simplifying your coding process and ensuring optimal application performance, keeping your bundle sizes lean.

As with any skill, mastery comes with practice. So, go ahead and try out these date-fns functions in your projects. Before long, you'll handle date manipulations in JavaScript like a pro. Happy coding!

divider-byrayray.png

Thanks

hashnode-footer.png

After reading this story, I hope you learned something new or are inspired to create something new! πŸ€— If I left you with questions or something to say as a response, scroll down and type me a message, send me a DM on Twitter @DevByRayRay

Want to receive new posts in your mailbox? No, not only a link, just the whole article without any ads πŸ€— or other stuff. Then subscribe to my newsletter πŸ‘. I promise I won’t spam you, only the most important and best-quality content will be sent to you ✌️.

Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. πŸ‘πŸ’°πŸŽ‰πŸ₯³πŸ”₯

0
Subscribe to my newsletter

Read articles from Dev By RayRay directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dev By RayRay
Dev By RayRay

πŸš€ Tech Lead / Lead Developer πŸ”₯ Writing about CSS, JavaScript, Typescript, Angular, Vue.js, Nuxt.js, Serverless functions, and a lot more web-related topics. https://byrayray.dev/