daterangepicker README

README проекта с github.com/dangrossman/daterangepicker. Одним файлом markdown: README.md.

Date Range Picker 4

Improvely.com

This date range picker component creates a dropdown menu from which a user can select a range of dates. I created it while building the UI for Improvely, which needed a way to select date ranges for reports.

Features include limiting the selectable date range, localizable strings and date formats, a single date picker mode, a time picker, and predefined date ranges.

Browser setup

Copy daterangepicker.js and daterangepicker.css to your site.

<link rel="stylesheet" href="daterangepicker.css">
<input id="dates" aria-label="Report dates">
<script src="daterangepicker.js"></script>
<script>
  const picker = new DateRangePicker('#dates', {
    locale: { format: 'YYYY-MM-DD' },
    ranges: { Today: [new Date(), new Date()] }
  });
  document.querySelector('#dates').addEventListener('apply.daterangepicker', event => {
    console.log(event.detail.startDate.toDate(), event.detail.endDate.toDate());
  });
</script>

Package and framework usage

import DateRangePicker from 'daterangepicker';
import 'daterangepicker/daterangepicker.css';

const picker = new DateRangePicker(inputElement, options, (start, end, label) => {
  console.log(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'), label);
});

Create the picker after its element mounts and call picker.remove() when it unmounts. In React, create it in useEffect and return the cleanup function. In Vue, use onMounted and onBeforeUnmount. In Angular, use ngAfterViewInit and ngOnDestroy. Importing the module is safe during server rendering. TypeScript declarations ship with the package. CommonJS callers can use require('daterangepicker'). Browser modules can import the standalone daterangepicker.mjs directly.

Use setStartDate, setEndDate and setRanges to update a mounted picker. Pass null to setRanges to remove the preset list. A second constructor call on the same element replaces the first picker. DateRangePicker.getInstance(element) returns its current instance.

Existing installations

Keep the application's existing jQuery and Moment script tags when replacing the picker file. The classic build registers $.fn.daterangepicker and the lowercase window.daterangepicker constructor. With Moment available, callbacks and date properties use genuine Moment objects with the application's locale and plugins. CommonJS also discovers installed legacy peers. Applications that use these libraries directly should declare them as their own dependencies.

For ES modules that keep jQuery or Moment private to the module, register the imported copies once before initializing legacy widgets:

import $ from 'jquery';
import moment from 'moment';
import DateRangePicker from 'daterangepicker';

DateRangePicker.installJQuery($, moment);
$('#dates').daterangepicker(options);

The plugin supports chaining, $.fn.daterangepicker.defaultOptions, .data('daterangepicker'), and namespaced events with the picker as the second argument. Native listeners receive the picker in event.detail. A committed input value dispatches a bubbling change event. Standalone date values support mutable date arithmetic, comparisons, cloning, formatting, and conversion to JavaScript dates with toDate().

Additional options and interactions

Development

Edit src/picker.js for picker behavior and src/dates.js for standalone date handling. Run npm ci, npm run build, and npm test to rebuild both distributions and exercise the browser and legacy interfaces.

Documentation website

Set the HTTP server's document root to website/ and open / to see the v4 documentation. The checked-in files serve directly without a build or redirect. The framework demos ship with local browser bundles. Their source and rebuild commands are in the examples guide.

Install the documentation build dependencies with npm ci and npm --prefix example/integrations ci. Run npm run docs:build to refresh the library files, demos and downloadable archive in website/. The build also exports the same layout to dist/docs/.

The public documentation is available at daterangepicker.com.

See It In a Live Application

License

The MIT License (MIT)

Copyright (c) 2012-2026 Dan Grossman

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

daterangepicker (dangrossman/daterangepicker)

Ищем в базе…

Что это такое?JavaScript-компонент, который отображает выпадающий календарь для выбора диапазона дат, одной даты или даты со временем и прикрепляется к полю ввода.
Это отдельный виджет или полноценный фреймворк для интерфейсов?Это один виджет (плагин jQuery), который подключается к существующему элементу input, а не фреймворк.
Как мне добавить его в проект?Подключите jQuery и Moment.js, затем загрузите JS- и CSS-файлы плагина и инициализируйте его на элементе input.
Какие библиотеки ему нужны?Он использует jQuery для работы с DOM и обработки событий, а также Moment.js для разбора и форматирования дат.
Можно ли ограничить, какие даты доступны для выбора?Да, ограничение доступного диапазона дат входит в число встроенных возможностей.
Зачем это было создано?Автор создал его во время разработки интерфейса для продукта Improvely, которому нужен был способ выбирать диапазоны дат для отчётов.
Можно ли выбрать одну дату со временем?Да, помимо выбора диапазона есть режим выбора одной даты и режим выбора времени.
Можно ли использовать готовые диапазоны вроде 'Last 7 Days'?Да, готовые диапазоны дат входят в число встроенных возможностей.
Можно ли локализовать текст и форматы дат?Да, локализуемые строки и форматы дат поддерживаются из коробки.
Какие есть похожие проекты?jquery-ui, layui, slick, dayjs, luxon, select2, simplefolio, material-ui
В каких он темах?jquery, ui-components, ui, frontend, library, javascript, web, mit, open-source
Автор
dangrossman
Размер
2.9 MB
Звёзды
11K
Возраст
14 г
Коммиты · 90 дней