Skip to content Skip to footer

JavaScript Add Days to Date: A Deep Dive

Hey there, fellow coders! Today, we’re tackling the common task of adding days to a date in JavaScript. Whether you’re building a booking system or just need to remind yourself when to water the plants, manipulating dates is a skill you’ll use time and time again.

Vanilla JavaScript – The Classic Approach

Let’s kick things off with good ol’ vanilla JavaScript. No fancy frameworks, just straight-up code that gets the job done. Here’s how you add days to a date:

function addDays(date, daysToAdd) {
  const copy = new Date(Number(date));
  copy.setDate(date.getDate() + daysToAdd);
  return copy;
}

const today = new Date();
const nextWeek = addDays(today, 7);

console.log(`Today is: ${today.toDateString()}`);
console.log(`Next week will be: ${nextWeek.toDateString()}`);

In this snippet, we create a function addDays that takes a date object and a number of daysToAdd. We make a copy of the original date (to avoid mutating it) and use the setDate method combined with getDate to move it forward in time. Easy peasy!

Moment.js – The Time Savior

For those who love working with libraries, Moment.js has been a go-to for date manipulation. Although it’s considered a bit bulky these days, and the team has recommended looking for alternatives, it’s still widely used and worth knowing how to handle.

const moment = require('moment');

function addDaysWithMoment(date, daysToAdd) {
  return moment(date).add(daysToAdd, 'days').toDate();
}

const todayMoment = new Date();
const nextWeekMoment = addDaysWithMoment(todayMoment, 7);

console.log(`Today is: ${todayMoment.toDateString()}`);
console.log(`Next week will be: ${nextWeekMoment.toDateString()}`);

Here, we’re using Moment’s add method, specifying the number of days to add. The toDate method is used to convert the moment object back to a JavaScript date object.

Date-fns – The Modern Toolkit

Date-fns is like lodash for dates. It’s modular, so you only need to include what you use, which makes it a lightweight and efficient choice for modern web development.

const addDays = require('date-fns/addDays');

const todayDateFns = new Date();
const nextWeekDateFns = addDays(todayDateFns, 7);

console.log(`Today is: ${todayDateFns.toDateString()}`);
console.log(`Next week will be: ${nextWeekDateFns.toDateString()}`);

With date-fns, you simply import the addDays function and use it directly on your date. It’s intuitive and clean, and you don’t have to worry about mutating your original date since addDays returns a new date.

Luxon – The Intuitive Library

Luxon is a powerful and modern library for working with dates and times. Created by one of the Moment.js team members, it brings a fresh approach to date manipulation in JavaScript.

const { DateTime } = require('luxon');

function addDaysWithLuxon(date, daysToAdd) {
  return DateTime.fromJSDate(date).plus({ days: daysToAdd }).toJSDate();
}

const todayLuxon = new Date();
const nextWeekLuxon = addDaysWithLuxon(todayLuxon, 7);

console.log(`Today is: ${todayLuxon.toDateString()}`);
console.log(`Next week will be: ${nextWeekLuxon.toDateString()}`);

Luxon’s DateTime object is created from a JavaScript date, and then we use the plus method to add days. The toJSDate method converts it back to a standard date object.

That’s it for the first half of our date-traveling adventure! We’ve covered the classic vanilla JavaScript method and introduced three different libraries that can help simplify the process. Stay tuned for the second half, where we’ll explore more frameworks and their unique approaches to adding days to dates. Happy coding until then!

Day.js – The Lightweight Champion

Moving on to Day.js, a minimalist library that’s often hailed as a lighter alternative to Moment.js. Its API is super similar to Moment’s, which makes it a breeze for those transitioning from the older library.

const dayjs = require('dayjs');

function addDaysWithDayjs(date, daysToAdd) {
  return dayjs(date).add(daysToAdd, 'day').toDate();
}

const todayDayjs = new Date();
const nextWeekDayjs = addDaysWithDayjs(todayDayjs, 7);

console.log(`Today is: ${todayDayjs.toDateString()}`);
console.log(`Next week will be: ${nextWeekDayjs.toDateString()}`);

Just like with Moment.js, we use the add method, but this time with Day.js. The syntax is almost identical, which is great for those of us who appreciate consistency and simplicity.

Using Native Intl and Temporal (The Future of JavaScript Dates)

The JavaScript proposal for Temporal is an all-new, global Temporal object that provides a modern way to work with dates and times. While it’s still at the proposal stage, it’s exciting to think about how it could simplify date manipulation in JavaScript.

// Note: This is a future-facing example and may not work in current environments
// as Temporal is not yet implemented in all JavaScript runtimes.

const { Temporal } = require('proposal-temporal');

function addDaysWithTemporal(date, daysToAdd) {
  const temporalDate = Temporal.PlainDate.from(date);
  return temporalDate.add({ days: daysToAdd }).toString();
}

const todayTemporal = new Date();
const nextWeekTemporal = addDaysWithTemporal(todayTemporal, 7);

console.log(`Today is: ${todayTemporal.toDateString()}`);
console.log(`Next week will be: ${nextWeekTemporal}`);

Temporal aims to solve many of the issues with Date objects, including the complexities around time zones and daylight saving time. Keep an eye on this one, as it could become the future standard for date handling in JavaScript.

Roll Your Own – When You Need Something Custom

Sometimes, you just need to roll up your sleeves and write a custom function that fits your specific needs. Here’s a quick example of how you might do that:

function addDaysCustom(date, daysToAdd) {
  // Calculate the number of milliseconds in a day
  const millisecondsPerDay = 24 * 60 * 60 * 1000;
  // Convert the date to milliseconds, add the required days, and convert back to a date
  return new Date(date.getTime() + daysToAdd * millisecondsPerDay);
}

const todayCustom = new Date();
const nextWeekCustom = addDaysCustom(todayCustom, 7);

console.log(`Today is: ${todayCustom.toDateString()}`);
console.log(`Next week will be: ${nextWeekCustom.toDateString()}`);

In this function, we work directly with the number of milliseconds in a day to adjust the date. It’s a bit more low-level but gives you full control over the process.

Wrapping Up

There you have it, folks – a comprehensive look at adding days to dates in JavaScript using various methods and libraries. Whether you prefer the no-dependency approach of vanilla JavaScript, the convenience of libraries like Moment.js and Day.js, or the potential future-proofing of Temporal, there’s a solution for every scenario.

Remember, date manipulation can be tricky, especially when dealing with time zones and daylight saving time changes. Always test your date-related code thoroughly to ensure it behaves as expected in all situations.

Now go forth and manipulate those dates like a pro! Keep building amazing things, and never stop learning. Happy coding!