Find the Next Occurrence of a Weekday in JavaScript

To find the next given weekday, add ((target - current + 7) % 7) days to a Temporal.PlainDate, choosing whether a match today counts. Part of Date Arithmetic Without Mutations.

Why this scenario is tricky

The whole problem is the modular step and the today-counts decision. With dayOfWeek running 1 (Monday) to 7 (Sunday), the days to add is (target - today + 7) % 7; if that is 0 you are already on the target, and whether to return today or jump a full week is a product decision you must make explicit.

The modulo and the 'today counts' choiceA plain difference can be negativeThe modulo and the 'today counts' choicetarget - today (can be < 0)lands in the past(target - today + 7) % 7always forwardAdd 7 before the modulo, and decide explicitly if today counts.

Minimal working solution

import { Temporal } from '@js-temporal/polyfill';
function nextWeekday(from: Temporal.PlainDate, target: number /*1..7*/) {
  const add = ((target - from.dayOfWeek + 7) % 7) || 7; // never today; next week if same
  return from.add({ days: add });
}

Modular stepAdd ((target-today+7)%7) daysModular stepfrom, target(t-d+7)%7add days

Full production version

import { Temporal } from '@js-temporal/polyfill';
function nextWeekday(from: Temporal.PlainDate, target: number, includeToday = false) {
  const raw = (target - from.dayOfWeek + 7) % 7;
  const add = raw === 0 ? (includeToday ? 0 : 7) : raw;
  return from.add({ days: add });
}

Today-counts flagincludeToday decides the zero caseToday-counts flagfrom,targetraw % 7zero?includeTodayresult

Verification snippet

Next Weekday assertionsKey cases assert correctlyAssertions that prove the edge caseWed → next Mon+5 daysMon → next Mon+7 (excl today)includeToday Mon+0always forwardtrue

Common pitfalls

Next Weekday pitfallsCommon mistakes and their fixesWrongRighttarget - today onlynegative → past date+7 then % 7forward-onlyignore the today casesurprising resultincludeToday flagexplicit choice

Frequently Asked Questions

How do I find the next Monday from a given date?

Use dayOfWeek (1 = Monday … 7 = Sunday) and add ((target - current + 7) % 7) days to a Temporal.PlainDate. Adding 7 before the modulo keeps the result in the future; if the remainder is 0 you are on the target already.

Should the current day count as the next occurrence?

That is a product decision, so make it explicit with a flag. When the modular difference is 0, either return today (includeToday) or add a full week to get the following occurrence.