How to get the next X day using DayJS

This article was published on Jul 13, 2023, and takes approximately a minute to read.

Date manipulation is quite tricky in JavaScript.

Every time I need to do that, I use a library called DayJS to ease those operations.

It's tiny, flexible, and has many nice plugins, localization, duration, and more.

Today I had to solve the following problem:

"given the '2023-07-10' date, how do I get the next following Friday?"

It seems easy, but it has some complexity on that.

I found there's a plugin in DayJS called Weekday.

So, all I needed to do was add this plugin to my dayjs function and, from that date specifically, get the "Friday weekday" and then format it:

import dayjs from "dayjs";
import weekOfYearPlugin from "dayjs/plugin/weekOfYear";

dayjs.extend(weekOfYearPlugin);

const date = dayjs("2023-07-10");
console.log(date.format("LLLL")); // Monday, July 10, 2023 12:00 AM

const nextFriday = date.weekday(5);
console.log(nextFriday.format("LLLL")); // Friday, July 14, 2023 12:00 AM

The only thing we must be aware of is the first day of the week.

If the first day and our date is Sunday, weekday(5) will be the next Friday.

If the first day is Monday and our date is Sunday, weekday(5) will be the past Friday.

References