DEV Community

シムツール
シムツール

Posted on

Counting business days between two dates (without a library)

"How many working days until the deadline?" sounds trivial until you actually code it.
Calendar dates are full of edge cases. Here's a clean way to count business days in plain
JavaScript, plus the gotchas to watch for.

The naive version

Business days = all days between two dates, minus weekends. The simplest correct approach is
to walk day by day and count the ones that aren't Saturday or Sunday:

function businessDaysBetween(start, end) {
  const a = new Date(start);
  const b = new Date(end);
  if (a > b) return -businessDaysBetween(end, start); // handle reversed range
  let count = 0;
  const d = new Date(a);
  while (d <= b) {
    const day = d.getDay();        // 0 = Sun, 6 = Sat
    if (day !== 0 && day !== 6) count++;
    d.setDate(d.getDate() + 1);
  }
  return count;
}
Enter fullscreen mode Exit fullscreen mode

Walking day-by-day is O(n) in the number of days, which is totally fine for human-scale ranges
(years, not millennia). It's also far easier to get right than clever modular-arithmetic formulas.

The gotchas

1. Inclusive vs exclusive endpoints. Decide whether both the start and end date count.
The loop above is inclusive of both ends. If you want "days remaining," you usually exclude
today (start from tomorrow).

2. Time zones / DST. If you build dates from user input, keep them at a fixed time (e.g. local
midnight) and avoid mixing UTC and local accessors. Iterating with setDate(+1) is DST-safe
because it operates on the calendar date, not on a fixed number of milliseconds — don't replace it
with + 86400000, which can drift across DST boundaries.

3. Holidays. Weekends are universal; holidays are not. They depend on country, region, and year.
A weekends-only calculation is honest and predictable; bolting on a holiday list means picking a
locale and keeping it updated. Be explicit about which one you're doing.

4. Reversed ranges. Users will enter the end before the start. Decide whether that's an error
or a signed (negative) result, and handle it deliberately.

When you just need the answer

If you don't want to wire this up yourself, I built a small set of date tools that do the
day-difference, add/subtract, age, and business-day calculations in the browser (no signup,
nothing sent to a server):

👉 Date calculators: https://date.simtool.dev/

The business-days tool counts inclusively and removes weekends only (no holiday list), which keeps
the result predictable across regions — matching the approach above.

Takeaway

For business-day math, a day-by-day walk is simpler and more correct than a formula. Nail down
inclusivity, keep date iteration DST-safe, and be explicit about holidays.


Disclosure: the linked date tools are a free project I built. Sharing it because it's the same
logic described here.

Top comments (0)