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.
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 });
}
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 });
}
Verification snippet
Common pitfalls
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.