Back to Blog
Laptop and calendar on desk
Tutorial
7 min read

JavaScript Date Range Picker: Build One With No Dependencies

By SimpleCalendarJS Team

SimpleCalendarJS~14 KB gzipped · Zero dependencies · Any framework
Short answer

To build a JavaScript date range picker with no dependencies, render a month grid of buttons. The first click sets the start date, the second sets the end, and if the second date is earlier you swap them. Highlight the days in between, and save both dates as local yyyy-mm-dd strings. If you only need two fields, two native date inputs can do the job.

Hotel stays, report filters, leave requests and rental bookings all need a start date and an end date, and users expect to pick both on one calendar. A JavaScript date range picker looks simple, but the details are easy to get wrong: date order, hover previews, day-count off-by-ones and timezone bugs. This guide covers three approaches: native inputs, a dependency-free component you write yourself, and the libraries worth considering in 2026.

What a JavaScript Date Range Picker Has to Handle

Before writing any code, list what "working" means. A date range picker that users don't fight with handles all of these:

  • Two-step selection. The first click sets the start and the second sets the end. A third click starts a new range.
  • Reversed clicks. If the second click is before the first, swap the dates instead of rejecting the click.
  • A hover preview. While the end date isn't chosen yet, highlight the days between the start and the day under the pointer (or keyboard focus).
  • Bounds. Block past dates, dates beyond a booking window, or unavailable days.
  • Correct dates. Store the range as local calendar dates (2026-12-18), not as UTC timestamps that move a day in some time zones.
  • A clear summary. Show "18 – 22 Dec 2026 · 4 nights" so the user can confirm the range without counting cells.
  • Accessibility. Real buttons, labels a screen reader can read, and a status message announced when the selection changes.

Every approach below covers a different share of this list.

Option 1: Two Native Date Inputs

If you only need two form fields, the browser already gives you most of the work. A native input type="date" selects one date, not a range, but two of them with linked min and max values make a usable range input with zero JavaScript libraries. According to MDN, the value is always yyyy-mm-dd whatever the display locale, and dates outside min/max are disabled in the picker and fail validation.

<form id="report-filter"> <label>From <input type="date" id="from" name="from" required></label> <label>To <input type="date" id="to" name="to" required></label> <button type="submit">Run report</button> </form> <script> const from = document.getElementById('from'); const to = document.getElementById('to'); // Keep the end on or after the start, and the start on or before the end from.addEventListener('change', () => { to.min = from.value; if (to.value && to.value < from.value) to.value = from.value; }); to.addEventListener('change', () => { from.max = to.value; }); </script>

Comparing the two values as strings works because yyyy-mm-dd sorts lexicographically. This approach suits admin filters and internal tools. Its limits are clear: the range isn't drawn on one calendar, the picker UI differs from browser to browser, and you can't style the popup. The constraint checks are a convenience; validate the range on the server as well.

Need a calendar in your app?

SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.

Option 2: Build a Date Range Picker From Scratch

When you need one calendar with a highlighted range, the code is manageable without a library. The component below renders a month grid with a CSS grid layout. It handles two-click selection with automatic swapping, previews the range on hover and keyboard focus, disables past dates, writes yyyy-mm-dd values to hidden inputs for form submission, and shows a localized summary using Intl.DateTimeFormat.

The markup and styles

<div class="drp"> <div class="drp-head"> <button type="button" data-nav="-1" aria-label="Previous month">‹</button> <strong id="drp-title"></strong> <button type="button" data-nav="1" aria-label="Next month">›</button> </div> <div class="drp-grid" id="drp-grid"></div> <p id="drp-summary" aria-live="polite">Pick a start date</p> </div> <form id="stay-form"> <input type="hidden" name="start" id="start"> <input type="hidden" name="end" id="end"> <button type="submit">Continue</button> </form>
.drp { width: 300px; font: 14px/1.4 system-ui, sans-serif; } .drp-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; } .drp-head button { border: 0; background: none; font-size: 20px; cursor: pointer; } .drp-grid { display: grid; grid-template-columns: repeat(7, 1fr); row-gap: 2px; } .drp-wd { text-align: center; font-size: 12px; color: #6b7280; padding: 4px 0; } .drp-grid button { border: 0; background: none; padding: 8px 0; cursor: pointer; } .drp-grid button:hover { background: #eef2ff; } .drp-grid button:disabled { color: #c4c4c4; cursor: not-allowed; background: none; } .drp-grid button.in-range { background: #e0e7ff; } .drp-grid button.range-start, .drp-grid button.range-end { background: #4f46e5; color: #fff; } .drp-grid button.range-start { border-radius: 6px 0 0 6px; } .drp-grid button.range-end { border-radius: 0 6px 6px 0; } .drp-grid button.range-start.range-end { border-radius: 6px; } .drp-grid button[aria-current="date"] { font-weight: 700; }

The JavaScript

const grid = document.getElementById('drp-grid'); const title = document.getElementById('drp-title'); const summary = document.getElementById('drp-summary'); const startInput = document.getElementById('start'); const endInput = document.getElementById('end'); const locale = navigator.language; const weekStartsOn = 1; // 0 = Sunday, 1 = Monday const DAY_MS = 86400000; const startOfDay = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate()); const today = startOfDay(new Date()); const minDate = today; // no past dates // Local date <-> 'yyyy-mm-dd' without ever going through UTC const toISODate = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; const parseLocal = (s) => { const [y, m, d] = s.split('-').map(Number); return new Date(y, m - 1, d); }; const sameDay = (a, b) => Boolean(a && b) && a.getTime() === b.getTime(); // Date.UTC removes daylight-saving 23/25-hour days from the difference const nightsBetween = (a, b) => Math.round( (Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) - Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / DAY_MS ); let viewYear = today.getFullYear(); let viewMonth = today.getMonth(); let start = null; let end = null; let hover = null; const titleFmt = new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric' }); const weekdayFmt = new Intl.DateTimeFormat(locale, { weekday: 'short' }); const labelFmt = new Intl.DateTimeFormat(locale, { dateStyle: 'full' }); const summaryFmt = new Intl.DateTimeFormat(locale, { dateStyle: 'medium' }); function build() { const first = new Date(viewYear, viewMonth, 1); title.textContent = titleFmt.format(first); grid.replaceChildren(); // Weekday headers: 7 Jan 2024 was a Sunday for (let i = 0; i < 7; i++) { const el = document.createElement('span'); el.className = 'drp-wd'; el.textContent = weekdayFmt.format(new Date(2024, 0, 7 + ((weekStartsOn + i) % 7))); grid.append(el); } // Empty cells before day 1 const offset = (first.getDay() - weekStartsOn + 7) % 7; for (let i = 0; i < offset; i++) grid.append(document.createElement('span')); const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate(); for (let day = 1; day <= daysInMonth; day++) { const date = new Date(viewYear, viewMonth, day); const btn = document.createElement('button'); btn.type = 'button'; btn.textContent = day; btn.dataset.date = toISODate(date); btn.setAttribute('aria-label', labelFmt.format(date)); btn.disabled = date < minDate; if (sameDay(date, today)) btn.setAttribute('aria-current', 'date'); grid.append(btn); } paint(); } function paint() { const preview = end || (start && hover); let lo = start; let hi = start; if (start && preview) [lo, hi] = start <= preview ? [start, preview] : [preview, start]; grid.querySelectorAll('button[data-date]').forEach((btn) => { const date = parseLocal(btn.dataset.date); btn.classList.toggle('in-range', Boolean(lo) && date >= lo && date <= hi); btn.classList.toggle('range-start', sameDay(date, lo)); btn.classList.toggle('range-end', sameDay(date, hi)); btn.setAttribute('aria-pressed', String(sameDay(date, start) || sameDay(date, end))); }); if (start && end) { const nights = nightsBetween(start, end); summary.textContent = `${summaryFmt.formatRange(start, end)} · ${nights} night${nights === 1 ? '' : 's'}`; startInput.value = toISODate(start); endInput.value = toISODate(end); } else { summary.textContent = start ? 'Pick an end date' : 'Pick a start date'; startInput.value = ''; endInput.value = ''; } } grid.addEventListener('click', (e) => { const btn = e.target.closest('button[data-date]'); if (!btn || btn.disabled) return; const date = parseLocal(btn.dataset.date); if (!start || end) { start = date; // first click, or start over after a complete range end = null; } else if (date < start) { end = start; // clicked backwards: swap start = date; } else { end = date; } hover = null; paint(); }); function previewFrom(e) { const btn = e.target.closest('button[data-date]'); if (!btn || btn.disabled || !start || end) return; hover = parseLocal(btn.dataset.date); paint(); } grid.addEventListener('mouseover', previewFrom); grid.addEventListener('focusin', previewFrom); grid.addEventListener('mouseleave', () => { hover = null; paint(); }); document.querySelectorAll('[data-nav]').forEach((btn) => btn.addEventListener('click', () => { const d = new Date(viewYear, viewMonth + Number(btn.dataset.nav), 1); viewYear = d.getFullYear(); viewMonth = d.getMonth(); build(); }) ); build();

Selection state lives in three variables (start, end, hover) and the DOM is just a projection of them. That makes the next steps straightforward: a maxDate, a set of booked dates to disable, or a second month side by side (render build() into two grids with consecutive months).

What this version leaves out

This version is fine for many forms, but be honest about what's missing before you ship it. It has no arrow-key navigation: every day is a tab stop, whereas the WAI-ARIA grid pattern uses a roving tabindex with arrow keys. It doesn't stop a range from spanning a disabled day in the middle (check start→end against your blocked set in the click handler). It also doesn't position itself as a popup next to an input. Each of these takes about an afternoon to add, and together they are most of what a library gives you.

Date Logic That Breaks Range Pickers

Most range picker bugs aren't UI bugs. They're date bugs, and they only show up for some users.

Date-only strings are parsed as UTC

MDN's Date.parse() documentation shows the trap: Date.parse("2019-01-01") implies UTC because it's date-only, while "2019-01-01T00:00:00" is read as local time. So new Date('2026-12-18') is midnight UTC, which is 17 December in New York. If you pass the values from a native date input or your API through new Date(), users west of UTC see every range shifted back a day. The parseLocal and toISODate helpers above avoid this: they split the string and build the date from local parts.

Nights versus days

18 to 22 December is 4 nights but 5 calendar days. Hotels and rentals count nights (check-out is exclusive). Leave requests and analytics filters usually count the end day (inclusive). Decide which one your backend means, name the fields to match (checkout versus lastDay), and test with a single-day range, which is either 0 nights or 1 day.

Daylight saving time

Subtracting two local Date objects across a DST change gives 23 or 25 hours, and Math.floor(diff / 86400000) loses a day. Converting both dates to Date.UTC(y, m, d) first, as nightsBetween does, makes every day exactly 86,400,000 ms.

Formatting the summary

Intl.DateTimeFormat.prototype.formatRange() produces the shortest correct range for the locale: MDN's example renders "Jan 10 – 20, 1906" when month and year are shared. It's listed as Baseline widely available since August 2021, so you don't need a date library to print "18 – 22 Dec 2026".

Date Range Picker Libraries Compared

If you'd rather not maintain the code above, these are the realistic options as of November 2026. Bundle sizes are left out wherever there was no primary source for them.

OptionDependenciesLicenseStatus (Nov 2026)Best for
Two native input type="date"NoneBrowser standardBuilt into every modern browserAdmin filters, internal forms
flatpickrNoneMITLatest GitHub release v4.6.13; 700+ open issuesPopup picker on an input, minDate/disable rules
Date Range Picker (Dan Grossman) v4None required; Moment and jQuery optionalMITActive; v4 core no longer needs jQueryReport filters with preset ranges ("Last 7 days")
easepickNoneMITArchived Jan 16, 2026Existing installs only
LitepickerNoneMITArchived Dec 18, 2023Existing installs only
SimpleCalendarJSNoneFree for personal/educational/open source; commercial license requiredVersion 3Inline range picker that matches a full event calendar

A few notes from the official docs:

  • flatpickr enables ranges with mode: "range". Its examples state that dates disabled by minDate, maxDate, enable or disable are not allowed in selections, which solves the "range spans a blocked day" problem for you. If you need a popup attached to an input with rich disable rules, this is the strongest dependency-free choice.
  • Date Range Picker was long known as the jQuery + Moment.js plugin. Version 4 is constructed with new DateRangePicker('#dates', options). Moment is optional, jQuery is only needed for the legacy $.fn.daterangepicker interface, and it supports ranges presets and minSpan/maxSpan limits. If you're still on the jQuery version, see jQuery UI Datepicker vs modern calendar libraries for the wider migration picture.
  • easepick and Litepicker both still install from npm, but their repositories are read-only. Don't start a new project on either.

Building It With SimpleCalendarJS

SimpleCalendarJS is a calendar component first (month, week, day and list views), and it also has a range-picker mode. It's worth considering when your app already shows events in a calendar and you want the range picker to look and behave the same, or when you want an inline range calendar without writing the grid logic above. It has zero dependencies and is about 14 KB gzipped (about 19 KB with the CSS). It's free for personal, educational and open source projects; commercial use needs a paid license.

Here's an inline stay picker that writes the range into a form:

<div id="stay-picker" style="max-width: 360px"></div> <form id="stay-form"> <input type="hidden" name="checkin" id="checkin"> <input type="hidden" name="checkout" id="checkout"> <p id="stay-summary" aria-live="polite">Select check-in and check-out dates.</p> <button type="submit" id="stay-submit" disabled>Check availability</button> <button type="button" id="stay-clear">Clear</button> </form>
import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; const checkin = document.getElementById('checkin'); const checkout = document.getElementById('checkout'); const summary = document.getElementById('stay-summary'); const submit = document.getElementById('stay-submit'); const startOfDay = (d) => { const x = new Date(d); x.setHours(0, 0, 0, 0); return x; }; const toISODate = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; const nightsBetween = (a, b) => Math.round((Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) - Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) / 86400000); const fmt = new Intl.DateTimeFormat('en-GB', { dateStyle: 'medium' }); function resetForm(message) { checkin.value = ''; checkout.value = ''; submit.disabled = true; summary.textContent = message; } function applyRange(rawStart, rawEnd) { if (!rawStart || !rawEnd) return; const start = startOfDay(rawStart); const end = startOfDay(rawEnd); // No min-date option in the picker, so validate here if (start < startOfDay(new Date())) { picker.clearSelection(); resetForm('Check-in can’t be in the past.'); return; } const nights = nightsBetween(start, end); if (nights < 1) { picker.clearSelection(); resetForm('Choose at least one night.'); return; } checkin.value = toISODate(start); checkout.value = toISODate(end); submit.disabled = false; summary.textContent = `${fmt.formatRange(start, end)} · ${nights} night${nights === 1 ? '' : 's'}`; } const picker = new SimpleCalendarJs('#stay-picker', { mode: 'range-picker', locale: 'en-GB', weekStartsOn: 1, weekdayFormat: 'narrow', onRangeSelect: applyRange, }); document.getElementById('stay-clear').addEventListener('click', () => { picker.clearSelection(); resetForm('Select check-in and check-out dates.'); });

To pre-fill a range (from a URL or a saved search), open the picker on that month with defaultDate and call setSelectedRange(start, end). Then call applyRange yourself so the form fields match:

const savedStart = new Date(2026, 11, 18); const savedEnd = new Date(2026, 11, 22); // pass defaultDate: savedStart in the options above, then: picker.setSelectedRange(savedStart, savedEnd); applyRange(savedStart, savedEnd);

In React, create the picker in an effect and destroy it on unmount:

import { useEffect, useRef } from 'react'; import SimpleCalendarJs from 'simple-calendar-js'; import 'simple-calendar-js/dist/simple-calendar-js.min.css'; export default function RangePicker({ onChange }) { const el = useRef(null); const onChangeRef = useRef(onChange); useEffect(() => { onChangeRef.current = onChange; }); useEffect(() => { const picker = new SimpleCalendarJs(el.current, { mode: 'range-picker', weekStartsOn: 1, onRangeSelect: (start, end) => { if (start && end) onChangeRef.current({ start, end }); }, }); return () => picker.destroy(); }, []); return <div ref={el} style={{ maxWidth: 360 }} />; }

Colors come from CSS custom properties such as --cal-primary and --cal-selected-bg on .uc-calendar, and adding the uc-dark class to a parent switches to the dark theme. See customising calendar themes for details. You can try the range-picker mode in the sandbox before installing anything.

The trade-offs are real. SimpleCalendarJS has no minDate, maxDate or disabled-dates option, which is why the example validates in onRangeSelect and clears invalid selections. It isn't a popup bound to an input either: it renders inline in a container, so you place it in your own dropdown or dialog. If greyed-out unavailable dates are central to your form, flatpickr or the from-scratch component above is the better fit. Where SimpleCalendarJS shines is a product that also needs a real calendar. For example, a rental site can use the same library for the guest's range picker and the owner's availability view (see building a property rental availability calendar and building a booking system in JavaScript).

Need a calendar in your app?

SimpleCalendarJS: ~14 KB gzipped, zero dependencies, works in any framework. Free for personal use.

Choosing the Right Approach

  1. Just need two fields in a form? Use two native date inputs with linked min/max. It ships no JavaScript and works on every device.
  2. Need one calendar with a highlighted range and full control? Start from the vanilla component above. It's under 150 lines, and you own every behaviour.
  3. Need a popup on an input with disabled dates or preset ranges? Use flatpickr (disable rules) or Date Range Picker v4 (presets and span limits). Both are MIT-licensed and work without jQuery.
  4. Need an inline range picker plus month/week/day event views in the same app? SimpleCalendarJS covers both with one dependency-free package. Check the docs for the full option list.

Whichever you choose, keep dates as local yyyy-mm-dd strings end to end, decide whether the end date is inclusive, and validate the range on the server.

Sources & Further Reading

Image Credits

Image free to use under the Pexels License.

Frequently Asked Questions

Can HTML input type=date select a date range?

No. A native date input holds one date. For a range, use two inputs, start and end, and keep them in order by setting the end input's min to the start value (and the start input's max to the end value) on change. The browser won't highlight the range or check it across fields, so validate it on the server too.

Why is my date range picker off by one day?

Most of the time a date-only string such as "2026-11-13" is going through new Date(). JavaScript reads date-only ISO strings as UTC midnight, so west of UTC they become the previous day. Split the string and call new Date(year, month - 1, day) instead, and format output from the local getFullYear, getMonth and getDate.

How do I count the nights between two dates in JavaScript?

Convert both local dates to UTC timestamps with Date.UTC(y, m, d), subtract them and divide by 86,400,000. Using Date.UTC keeps daylight saving changes from producing 23- or 25-hour days. Nights are that difference; for an inclusive day count, add one.

Should the end date of a range be inclusive or exclusive?

Choose one rule and document it in your API. Hotels treat check-out as exclusive (Dec 18–22 is four nights), while reports and leave requests usually count the end day. Storing exclusive end dates makes ranges easier to compare for overlaps, because one range's end can equal the next one's start.

Is flatpickr still a good choice for a date range picker?

Yes, for a popup picker attached to an input. It has no dependencies, is MIT-licensed, and supports range selection with mode: "range", plus minDate, maxDate and disable rules that range selections respect. Its latest GitHub release is v4.6.13, and the repository has hundreds of open issues, so test the features you rely on.

Does a date range picker need to handle time zones?

Usually not, if you treat the range as calendar dates and not instants. Store plain yyyy-mm-dd strings and avoid converting them to UTC timestamps. Time zones only come into play when the range has times, such as a check-in at 15:00 at a property in another zone. Then the server should resolve the date and time in the property's zone.

Add a calendar to your app today

Free for personal projects. $49/year or $199 lifetime per commercial project.

Keep Reading