日本語

How to Count Days Between Two Dates in React

​​React​JavaScript,Playwright,Temporal,TypeScript

To count the days between two dates, Temporal.PlainDate's until() works without any need to think about times or time zones. The same method can also produce a phrase like "1 month and 20 days." In browsers without Temporal, placing both dates at UTC midnight and subtracting gives the same day count.

Here I built a DayCounter component with two input type="date" fields. It shows the number of days, a "months and days" breakdown, and the number of days excluding weekends. The calculations are in dateDiff.ts.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I converted the .tsx files with esbuild, confirmed there were no type errors with tsc, and then drove a development build wrapped in StrictMode with Playwright. I did not test Firefox, Safari, entering dates on a smartphone, or screen reader announcements. I tested behavior in browsers without Temporal by using a Chromium page with Temporal removed.

Two date fields with start date 11/05/2026 and end date 12/25/2026, and a checked checkbox labeled "count the start date as day 1." Below them, large light-blue text reads "51 days," followed by "1 month 21 days" and "37 days excluding weekends."
Counting from November 5, 2026 to December 25, 2026, including the start date

In the test environment, Chromium displayed the date fields in month/day/year order. According to MDN's explanation of input type="date", the display format changes with the browser locale, but value is always in the yyyy-mm-dd form. The functions below take this value string as is.

Counting days with Temporal.PlainDate's until()

This is the file with the calculation functions.

ts
// Function that computes the difference between two input type="date" values ("YYYY-MM-DD")

const MS_PER_DAY = 86_400_000;
const hasTemporal = typeof Temporal !== 'undefined';

// For browsers without Temporal: day number counted from 1970-01-01 (in UTC)
function utcDayNumber(value: string): number {
  const [y, m, d] = value.split('-').map(Number);
  const date = new Date(0);
  date.setUTCFullYear(y, m - 1, d); // Date.UTC would map years 0–99 to the 1900s
  return date.getTime() / MS_PER_DAY;
}

// Number of days from start to end (end − start). Negative if end is earlier.
// useTemporal is a parameter for comparing the two methods
export function diffDays(start: string, end: string, useTemporal = hasTemporal): number {
  if (useTemporal) {
    return Temporal.PlainDate.from(start).until(end).days;
  }
  return utcDayNumber(end) - utcDayNumber(start);
}

// Years, months, and days. With inclusive, counts up to the day after end. Returns null without Temporal.
export function diffYmd(start: string, end: string, inclusive = false) {
  if (!hasTemporal) return null;
  const to = Temporal.PlainDate.from(end).add({ days: inclusive ? 1 : 0 });
  const d = Temporal.PlainDate.from(start).until(to, { largestUnit: 'years' });
  return { years: d.years, months: d.months, days: d.days };
}

// Day of week (0 = Sunday … 6 = Saturday)
export function dayOfWeek(value: string): number {
  return new Date(utcDayNumber(value) * MS_PER_DAY).getUTCDay();
}

// Number of weekdays among the length days starting from the weekday firstDow
export function countWeekdays(firstDow: number, length: number): number {
  let count = Math.floor(length / 7) * 5;
  for (let i = 0; i < length % 7; i++) {
    const dow = (firstDow + i) % 7;
    if (dow !== 0 && dow !== 6) count++;
  }
  return count;
}

Temporal.PlainDate is a calendar date with no time and no time zone. until() returns the length up to the other date as a Temporal.Duration. The options for until() are the same as those for since(). According to MDN's explanation of the since() options, if you don't specify largestUnit, the largest unit is days, so .days is the day count itself. According to MDN's explanation of until(), if the other date is earlier, the length is negative. In the test environment, the days from 2026-03-01 to 2026-01-31 was -29.

When a date field is empty, its value is an empty string. In the test environment, Temporal.PlainDate.from('') threw a RangeError. So the component calls the calculation only when both fields have values.

In TypeScript, I type-checked with esnext in the lib setting of tsconfig.json. Setting lib to es2025 produced the error "Cannot find name 'Temporal'".

Without Temporal, subtract UTC dates

According to MDN's browser compatibility data, Temporal.PlainDate is supported starting with Chrome 144 and Firefox 139, and Safari offers it only in Technology Preview (checked on November 5, 2026). So when Temporal is absent, utcDayNumber converts each date into a day count from January 1, 1970, and then subtracts. I opened a Chromium page with Temporal removed and counted from November 5, 2026 to December 25, 2026. The UI showed "50 days" and "36 days excluding weekends." Only the "months and days" line was missing.

In my earlier article, "How to Create Start and End Date Inputs in React," I used Date.parse to confirm that handling dates in UTC is not affected by daylight saving time. Here I compared whether the results of Temporal and utcDayNumber match. I changed the time zone to America/New_York, Europe/London, Australia/Sydney, and Asia/Tokyo, and counted periods that span the days when daylight saving time starts or ends in each region. Both methods gave 2 days. I also compared 100,000 random pairs of dates with years from 1 to 9999, and every result matched.

I used setUTCFullYear to set the year instead of Date.UTC(year, month, day) because of years with two digits or fewer. According to MDN's explanation of Date.UTC(), Date.UTC treats years 0 to 99 as 1900 to 1999. The date fields also accept typed years such as "0050". From January 1, 0050 to January 1, 2026, Date.UTC gave 27,759 days, while setUTCFullYear and Temporal gave 721,719 days.

"X months and Y days" can look wrong across month ends

Passing { largestUnit: 'years' } to until() returns the length split into years, months, and days. Here are the results when counting from month-end dates:

Start date End date until() result Days
2026-01-31 2026-02-27 27 days 27
2026-01-31 2026-02-28 28 days 28
2026-01-31 2026-03-01 1 month 1 day 29
2026-01-31 2026-03-31 2 months 59
2026-02-28 2026-03-31 1 month 3 days 31
2024-02-29 2025-02-28 11 months 30 days 365
2024-02-29 2025-03-01 1 year 1 day 366

From January 31 to February 28, the count reaches the last day of February, but the result is "28 days," not "1 month." From January 31 to March 1, the result is "1 month 1 day." The day count differs by only one day, yet the display changes a lot. Counting from February 29, 2024, even on February 28, 2025 the result is "11 months 30 days," and only on March 1 does it become "1 year 1 day."

According to MDN's explanation of add(), if the target month doesn't have that day, the date is moved to the nearest valid day in that month (February 30 becomes February 28 or 29). In the test environment, adding one month to January 31, 2026 gave February 28. Because month lengths differ, "X months and Y days" can't be determined in just one way. The component shows the day count prominently and adds the "months and days" only as a supplement.

Letting the user choose whether to count the start date

The day count from until() does not include the start date. From November 5 to November 9 is 4 days. When you want both ends counted, as with the length of a trip, add 1.

The component switches this with a checkbox labeled "count the start date as day 1." When it is checked, 1 is added to the day count, and the "months and days" is measured up to the day after the end date. From January 1 to January 31, 2026, without the checkbox the UI showed "30 days" and "30days." With the checkbox checked, it showed "31 days" and "1 month."

Counting days excluding weekends

countWeekdays takes the weekday of the first day counted and the number of days, and returns the number of days excluding Saturdays and Sundays. It adds 5 for every full set of 7 days and checks the weekday of each leftover day one at a time. Without the checkbox, it counts from the day after the start date. With the checkbox, it counts from the start date itself. Public holidays are not counted.

From November 5, 2026 (Thursday) to November 9 (Monday), without the checkbox the UI showed "2 days excluding weekends" (Friday and Monday). With the checkbox, it showed "3 days" (Thursday, Friday, and Monday). I also compared the results for 2,000 randomly chosen pairs of dates and day counts against counting each day's weekday one at a time, and all of them matched.

Putting it together in a component

tsx
import { useId, useState } from 'react';
import { countWeekdays, dayOfWeek, diffDays, diffYmd } from './dateDiff';

type Props = { defaultStart?: string; defaultEnd?: string };

export function DayCounter({ defaultStart = '', defaultEnd = '' }: Props) {
  const id = useId();
  const [start, setStart] = useState(defaultStart);
  const [end, setEnd] = useState(defaultEnd);
  const [countFirstDay, setCountFirstDay] = useState(false);

  return (
    <div className="day-counter">
      <label htmlFor={`${id}-start`}>開始日</label>
      <input
        id={`${id}-start`}
        type="date"
        max="9999-12-31"
        value={start}
        onChange={(e) => setStart(e.target.value)}
      />
      <label htmlFor={`${id}-end`}>終了日</label>
      <input
        id={`${id}-end`}
        type="date"
        max="9999-12-31"
        value={end}
        onChange={(e) => setEnd(e.target.value)}
      />
      <label className="check">
        <input
          type="checkbox"
          checked={countFirstDay}
          onChange={(e) => setCountFirstDay(e.target.checked)}
        />
        開始日も1日目として数える
      </label>
      <output htmlFor={`${id}-start ${id}-end`} aria-live="polite">
        {start && end ? (
          <Result start={start} end={end} countFirstDay={countFirstDay} />
        ) : (
          <p>2つの日付を選んでください</p>
        )}
      </output>
    </div>
  );
}

function Result({ start, end, countFirstDay }: { start: string; end: string; countFirstDay: boolean }) {
  const signed = diffDays(start, end);
  // Even if end is earlier, align the range to "earlier date → later date"
  const [from, to] = signed < 0 ? [end, start] : [start, end];
  const days = Math.abs(signed) + (countFirstDay ? 1 : 0);
  const firstDow = (dayOfWeek(from) + (countFirstDay ? 0 : 1)) % 7;
  const ymd = diffYmd(from, to, countFirstDay);

  return (
    <>
      <p className="days">
        <strong>{days.toLocaleString('ja-JP')}</strong> 日
      </p>
      {signed < 0 && <p>終了日のほうが前なので、入れ替えて数えています</p>}
      {ymd && (
        <p>
          {ymd.years > 0 && `${ymd.years}年`}
          {ymd.months > 0 && `${ymd.months}か月`}
          {(ymd.days > 0 || (ymd.years === 0 && ymd.months === 0)) && `${ymd.days}日`}
        </p>
      )}
      <p>土日を除くと {countWeekdays(firstDow, days).toLocaleString('ja-JP')} 日</p>
    </>
  );
}
css
.day-counter {
  display: grid;
  grid-template-columns: max-content 1fr;
  gap: 8px 12px;
  align-items: center;
  max-width: 360px;
}
.day-counter .check,
.day-counter output {
  grid-column: 1 / -1;
}
.day-counter output p {
  margin: 4px 0;
}
.day-counter .days strong {
  font-size: 2rem;
  color: #067a98;
}

If either date is empty, the component doesn't render Result and shows a "please select two dates" message instead. When I cleared the start date, the display switched to this message.

When the end date is earlier than the start date, the two dates are swapped before counting. With the start date set to December 25, 2026 and the end date set to November 5, the UI showed "50 days" and a note saying that the end date was earlier, so the dates were swapped for counting. Instead of stopping with an error, the component gives the day count in either order.

The two date fields have max="9999-12-31". I also introduced the four-digit year limit in my earlier article, "How to Create Start and End Date Inputs in React." When calculating with Temporal, though, the component disappears if you type five or more digits for the year without this limit. When I removed max from the start field and typed "123456" into the year, value changed with each digit. Once it reached the five-digit "12345-01-01", the page showed a RangeError. Passing the same string to Temporal.PlainDate.from() throws the same RangeError. Because the error happened during rendering, React removed the entire component from the screen, as described in React's reference on error boundaries.

In fields with max, typing the same way leaves the last four digits, "3456," and value becomes "3456-01-01". Apart from typing in the field with max removed, no errors or warnings appeared in the console.

​Posted by 86