← Back to JavaScript, page 10

javascript-0181 · Medium mid

How would you write safe date utilities: add days or months, count the days between two dates, and skip weekends?

Do calendar math in UTC, or on date-only values, so daylight saving changes cannot shift results. Add days with setUTCDate, clamp the day of month when adding months, count days by dividing the difference of UTC midnights by 86,400,000 and rounding, and skip weekends by checking getUTCDay. Never divide a local time difference by 24 hours.

Full answer

Date bugs come from three sources: time zones, daylight saving time (DST), and month lengths.

Rules that keep utilities correct:

  1. Decide whether the value is an instant (a moment in time) or a calendar date (a day with no time, like a birthday). For calendar dates, store YYYY-MM-DD, parse it as UTC parts with Date.UTC(y, m - 1, d), and use the getUTC* and setUTC* methods. A date-only string such as '2026-03-08' is parsed as UTC by Date.parse, but new Date(2026, 2, 8) uses local time, which is a common mix-up.
  2. Add days with setUTCDate(getUTCDate() + n). The engine handles month and year overflow. Do not add n * 86400000 to a local date, because a local day can be 23 or 25 hours long.
  3. Add months by setting the month, then clamping the day. Adding one month to January 31 should give the last day of February, not March 3, which is what the overflow of setMonth does.
  4. Count days between two calendar dates: take both as UTC midnights, divide the difference by 86,400,000 and Math.round. Using Math.floor or ceil on instants across a DST change gives off-by-one results.
  5. Business days: loop day by day and skip when getUTCDay() is 0 or 6, or compute it with weeks times five plus the remainder. Holidays need a calendar list passed as input.
  6. Format with toISOString().slice(0, 10) for UTC, or Intl.DateTimeFormat with an explicit timeZone when showing instants to users.
  7. Always make functions pure: return a new Date and do not mutate the argument. Inject now for tests.
  8. Validate input: Number.isNaN(date.getTime()) detects an invalid date, and new Date(2026, 1, 31) silently becomes March 3.

For anything beyond this (recurrence rules, other calendars, zones), use Intl, the Temporal API where available, or a tested library.

javascript
const DAY = 86400000;
const parse = (iso) => {
  const [y, m, d] = iso.split('-').map(Number);
  return new Date(Date.UTC(y, m - 1, d));
};
const format = (date) => date.toISOString().slice(0, 10);

function addDays(date, n) {
  const copy = new Date(date);
  copy.setUTCDate(copy.getUTCDate() + n);
  return copy;
}

function addMonths(date, n) {
  const day = date.getUTCDate();
  const result = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + n, 1));
  const lastDay = new Date(Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)).getUTCDate();
  result.setUTCDate(Math.min(day, lastDay));
  return result;
}

const daysBetween = (a, b) => Math.round((b - a) / DAY);
const isWeekend = (date) => [0, 6].includes(date.getUTCDay());

function addBusinessDays(date, n, holidays = new Set()) {
  let current = new Date(date);
  let left = Math.abs(n);
  const step = n < 0 ? -1 : 1;
  while (left > 0) {
    current = addDays(current, step);
    if (!isWeekend(current) && !holidays.has(format(current))) left--;
  }
  return current;
}

const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
const startOfWeekMonday = (date) => addDays(date, -((date.getUTCDay() + 6) % 7));

console.log(format(addDays(parse('2026-12-30'), 5)), format(addDays(parse('2026-03-01'), -1)));
console.log(format(addMonths(parse('2026-01-31'), 1)), format(addMonths(parse('2024-01-31'), 1)), format(addMonths(parse('2026-11-15'), 3)), format(addMonths(parse('2026-03-31'), -1)));
console.log(daysBetween(parse('2026-01-01'), parse('2026-12-31')), daysBetween(parse('2026-03-09'), parse('2026-03-08')));
console.log(format(addBusinessDays(parse('2026-12-04'), 1)), format(addBusinessDays(parse('2026-12-04'), 5)), format(addBusinessDays(parse('2026-12-07'), -1)));
console.log(format(addBusinessDays(parse('2026-12-23'), 3, new Set(['2026-12-25']))));
console.log(isLeapYear(2024), isLeapYear(2100), isLeapYear(2000), format(startOfWeekMonday(parse('2026-12-06'))));

const naiveMonth = new Date(Date.UTC(2026, 0, 31));
naiveMonth.setUTCMonth(naiveMonth.getUTCMonth() + 1);
console.log('naive setMonth overflow:', format(naiveMonth));
console.log('invalid date check:', Number.isNaN(new Date('2026-13-45').getTime()), '| silent overflow:', format(new Date(Date.UTC(2026, 1, 31))));

const midnightBefore = Date.parse('2026-03-08T05:00:00Z');
const midnightAfter = Date.parse('2026-03-09T04:00:00Z');
const hours = (midnightAfter - midnightBefore) / 3600000;
console.log('New York, 8 March to 9 March 2026 is', hours, 'hours:', 'floor gives', Math.floor(hours / 24), 'days, round gives', Math.round(hours / 24));
const fmt = new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', dateStyle: 'medium', timeStyle: 'short' });
console.log(fmt.format(midnightBefore), '->', fmt.format(midnightAfter));

Run with Node.js v24.22.1 as js-181.js; two runs gave identical output. Output: 2027-01-04 2026-02-28 2026-02-28 2024-02-29 2027-02-15 2026-02-28 364 -1 2026-12-07 2026-12-11 2026-12-04 2026-12-29 true false true 2026-11-30 naive setMonth overflow: 2026-03-03 invalid date check: true | silent overflow: 2026-03-03 New York, 8 March to 9 March 2026 is 23 hours: floor gives 0 days, round gives 1 Mar 8, 2026, 12:00 AM -> Mar 9, 2026, 12:00 AM

Key points

  • Separate instants from calendar dates; do calendar math in UTC.
  • Add days with setUTCDate; clamp the day when adding months.
  • Count days between UTC midnights and round, never divide local times by 24 hours.
  • Skip weekends with getUTCDay; holidays need an input list.
  • Return new dates, validate input, and inject now for tests.

Common mistakes

  • Dividing a local time difference by 24 hours and flooring the result.
  • Using setMonth on the 31st and landing in the next month.
  • Mixing local constructors and date-only string parsing.
  • Mutating the date that was passed in.

Follow-ups

  • How would the business day function change for a custom weekend?
  • How would Temporal's PlainDate make this simpler?
  • How do you show an instant in the user's time zone?

Tips

  • Ask whether the value is an instant or a calendar date.
  • Name the DST case that breaks the 24-hour division.
  • Keep utilities pure and testable with an injected clock.