A JavaScript component that is a date & time range picker, no need to build, no dependencies except Moment.js, that is based on Dan Grossman's bootstrap-daterangepicker.

Overview

vanilla-datetimerange-picker

Overview.

A JavaScript component that is a date & time range picker, no need to build, no dependencies except Moment.js, that is inspired by Dan Grossman's bootstrap-daterangepicker.

Actually, this program is base on Dan Grossman's bootstrap-daterangepicker (version 3.1). I just changed the code a bit to not need jquery.

Requirements

IE11

If you want to use on Internet Explorer 11, include Polyfill to use CustomEvent, Object.assign, Element.prototype.closest and Element.prototype.matches features.

Quick start using CDN.

  1. Include Moment.js and Date Range Picker's css and js files in your webpage:
<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/gh/alumuko/vanilla-datetimerange-picker@latest/dist/vanilla-datetimerange-picker.css">

<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/gh/alumuko/vanilla-datetimerange-picker@latest/dist/vanilla-datetimerange-picker.js"></script>
  1. Put "INPUT" element into "BODY", and bind DateRangePicker instance.
<input type="text" id="datetimerange-input1" size="24" style="text-align:center">

<script>
    window.addEventListener("load", function (event) {
        new DateRangePicker('datetimerange-input1');
    });
</script>

See simple example page.

Usage

new DateRangePicker(bindElement, options, callback);
parameter type description
bindElement string or object bind element id or bind HTMLElement object
options object option set (see Options)
callback function(momemt, moment) change datetime callback, 2 parameters: start and end datetime

Options

Almost same as Dan Grossman's bootstrap-daterangepicker Version 3.1
name type description
startDate Date or string The beginning date of the initially selected date range. If you provide a string, it must match the date format string set in your locale setting.
endDate Date or string The end date of the initially selected date range.
minDate Date or string The earliest date a user may select.
maxDate Date or string The latest date a user may select.
maxSpan object The maximum span between the selected start and end dates. You can provide any object the moment library would let you add to a date.
showDropdowns true/false Show year and month select boxes above calendars to jump to a specific month and year.
minYear number The minimum year shown in the dropdowns when showDropdowns is set to true.
maxYear number The maximum year shown in the dropdowns when showDropdowns is set to true.
showWeekNumbers true/false Show localized week numbers at the start of each week on the calendars.
showISOWeekNumbers true/false Show ISO week numbers at the start of each week on the calendars.
timePicker true/false Adds select boxes to choose times in addition to dates.
timePickerIncrement number Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30).
timePicker24Hour true/false Use 24-hour instead of 12-hour times, removing the AM/PM selection.
timePickerSeconds true/false Show seconds in the timePicker.
ranges object Set predefined date ranges the user can select from. Each key is the label for the range, and its value an array with two dates representing the bounds of the range. See example code.
showCustomRangeLabel true/false Displays "Custom Range" at the end of the list of predefined ranges, when the ranges option is used. This option will be highlighted whenever the current date range selection does not match one of the predefined ranges. Clicking it will display the calendars to select a new range.
alwaysShowCalendars true/false Normally, if you use the ranges option to specify pre-defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range". When this option is set to true, the calendars for choosing a custom date range are always shown instead.
opens 'left'/'right'/'center' Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to.
drops 'down'/'up'/'auto' Whether the picker appears below (default) or above the HTML element it's attached to.
buttonClasses string CSS class names that will be added to both the apply and cancel buttons.
applyButtonClasses string CSS class names that will be added only to the apply button.
cancelButtonClasses string CSS class names that will be added only to the cancel button.
singleDatePicker true/false Show only a single calendar to choose one date, instead of a range picker with two calendars. The start and end dates provided to your callback will be the same single date chosen.
autoApply true/false Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates are clicked.
linkedCalendars true/false When enabled, the two calendars displayed will always be for two sequential months (i.e. January and February), and both will be advanced when clicking the left or right arrows above the calendars. When disabled, the two calendars can be individually advanced and display any month/year.
isInvalidDate function(moment) A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not.
isCustomDate function(moment) A function that is passed each date in the two calendars before they are displayed, and may return a string or array of CSS class names to apply to that date's calendar cell.
autoUpdateInput true/false Indicates whether the date range picker should automatically update the value of the <input> element it's attached to at initialization and when the selected dates change.
parentEl string the parent element that the date range picker will be added to, if not provided this will be 'body'
locale object
locale.format string date time text locale format like "YYYY年MM月DD日 HH時mm分ss秒".
locale.separator string separator between 2 date times. default separator is "-"
locale.applyLabel string label text of the apply button. default is "Apply"
locale.cancelLabel string label text of the cancel button. default is "Cancel"
locale.weekLabel string label text of week number column like "W"
locale.daysOfWeek array of 7 strings 7 label texts of week column like ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
locale.monthNames array of 12 strings 12 label texts of month nameweek column. like ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
locale.firstDay number 0 = from Sunday, 1 = from Monday, ..., 6 = from Saturday

strong text value means default value.

Methods

You can programmatically update the startDate and endDate in the picker using the setStartDate and setEndDate methods. You can access the Date Range Picker object and its functions and properties through data properties of the element you attached it to.
name type description
setStartDate Date or string Sets the date range picker's currently selected start date to the provided date
setEndDate Date or string Sets the date range picker's currently selected end date to the provided date

Usage

    let drp = new DateRangePicker('datetimerange-input1', { alwaysShowCalendars: true });,
    drp.setStartDate('2014/03/01');
    drp.setEndDate('2014/03/03');

Events

Several events are triggered on the element you attach the picker to, which you can listen for.
name description
show.daterangepicker Triggered when the picker is shown
hide.daterangepicker Triggered when the picker is hidden
showCalendar.daterangepicker Triggered when the calendar(s) are shown
hideCalendar.daterangepicker Triggered when the calendar(s) are hidden
apply.daterangepicker Triggered when the apply button is clicked, or when a predefined range is clicked
cancel.daterangepicker Triggered when the cancel button is clicked

Usage

    window.addEventListener('apply.daterangepicker', function (ev) {
        console.log(ev.detail.startDate.format('YYYY-MM-DD'));
        console.log(ev.detail.endDate.format('YYYY-MM-DD'));
    });

Examples

Data Time Range Picker with a Callback.

Data Time Range Picker

<input type="text" id="datetimerange-input1" size="40" style="text-align:center">

<script>
    window.addEventListener("load", function (event) {
        new DateRangePicker('datetimerange-input1',
            {
                timePicker: true,
                opens: 'left',
                ranges: {
                    'Today': [moment().startOf('day'), moment().endOf('day')],
                    'Yesterday': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
                    'Last 7 Days': [moment().subtract(6, 'days').startOf('day'), moment().endOf('day')],
                    'This Month': [moment().startOf('month').startOf('day'), moment().endOf('month').endOf('day')],
                },
                locale: {
                    format: "YYYY-MM-DD HH:mm:ss",
                }
            },
            function (start, end) {
                alert(start.format() + " - " + end.format());
            })
    });
</script>

See datetime example page

Extra

A Dark Version CSS

Dark Data Time Range Picker

change

<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/gh/alumuko/vanilla-datetimerange-picker@latest/dist/vanilla-datetimerange-picker.css">

to

<link type="text/css" rel="stylesheet" href="https://cdn.jsdelivr.net/gh/alumuko/vanilla-datetimerange-picker@latest/extra/vanilla-datetimerange-picker-dark.css">

See datetime dark example page.

Special Thanks

Special thanks to Dan Grossman

License

MIT License

Comments
  • Update vanilla-datetimerange-picker.js

    Update vanilla-datetimerange-picker.js

    In use strict mode, using autoApply generates an error message Uncaught TypeError: e is undefined vanilla-datetimerange-picker.js:1476:13. By changing these two lines the error disappears.

    opened by spin0us 0
  • fix syntax error (parentEl.scrollTop and scrollLeft are not functions)

    fix syntax error (parentEl.scrollTop and scrollLeft are not functions)

    element.scrollTop and scrollLeft are not functions. Error occurs if parentEl option is set to other than document body. this.parentEl.scrollTop() -> this.parentEl.scrollTop this.parentEl.scrollLeft() -> this.parentEl.scrollLeft

    opened by mikkle 0
  • Input Initially Empty ?

    Input Initially Empty ?

    Hi, i would like to reproduce this example http://www.daterangepicker.com/#example5 Is it possible with your lib? When i set autoUpdateInput: false my input field always remains empty no matter what selection is made

    opened by costalfy 0
  • Allow ranges to be selected without closing the date picker

    Allow ranges to be selected without closing the date picker

    Currently, selecting a range for the date picker applies the range and then closes the date picker automatically. It might be nice instead to see the range confirmed first, then be able to cancel or apply. Could there be an option added that does this?

    opened by camilocalvo 0
  • Exclusion dates

    Exclusion dates

    I asked Dan Grossman also about it.

    I have a similar use for the date range picker, but a bit more advanced.

    I would like to preset all vacation and weekend days as not being valid dates throughout the whole year (read from a CSV file). Just before displaying the date range picker, all non-valid dates should be highlighted (grayed out in customizable color). When scrolling through the next month, the same routine should be used, meaning that you would visually see the dates that are not allowed as valid dates.

    Perhaps reading from a CSV file is too slow, so I would suggest pre-setting some 365-day ExclusionArray (which of course needs to be filled only once by means of the CSV file).

    opened by ko3st 0
  • How do I destroy/clear the DateRangePicker out of memory so that it doesn't exist anymore?

    How do I destroy/clear the DateRangePicker out of memory so that it doesn't exist anymore?

    Let's say I create the following one:

        let Test = new DateRangePicker('CalendarDiv', {
                startDate: moment().startOf('day'),
                singleDatePicker: true,
                showDropdowns: true,
                opens: 'right',
                minYear: 2000,
                maxYear: new Date().getFullYear(),
                maxDate: moment() //Stops user from choosing future dates
        }, function(start, end){
        });
    

    How would I go about destroying the object?

    Test = null;

    Is this possible? What is the best method?

    I don't want the object to exist anymore.

    opened by shaunroselt 0
Releases(0.2.0)
Owner
null
Bootstrap Persian/Gregorian Date Time Picker

MD.BootstrapPersianDateTimePicker Bootstrap 5+ Persian And Gregorian Date Time Picker Major changes: Using Bootstrap 5 jQuery Removed Rewrite all code

Mohammad Dayyan 305 Nov 23, 2022
Colr Pickr, a vanilla JavaScript color picker component built with SVGs, with features like saving colors. Similar design to the chrome-dev-tools color picker.

Colr Pickr Colr Pickr, a vanilla JavaScript color picking component built with SVGs, with features like saving colors. Similar design to the chrome-de

TEK 27 Jun 27, 2022
A lightweight (~2kB) library to create range sliders that can capture a value or a range of values with one or two drag handles

range-slider-input A lightweight (~2kB) library to create range sliders that can capture a value or a range of values with one or two drag handles. Ex

Utkarsh Verma 42 Dec 24, 2022
Generate release notes from git commit history either commit range or tag range.

Would you like to support me? Release Notes Generate release notes from git commit history either commit range or tag range. App Store Template Change

Numan 6 Oct 8, 2022
Tool Cool Color Picker is a color picker library written in typescript and using web component technologies.

Tool Cool Color Picker Tool Cool Color Picker is a color picker library written in typescript and using web component technologies. Check out the demo

Tool Cool 13 Oct 23, 2022
Simple date and time picker in vanilla javascript

simplepicker Simple datetime picker in vanilla javascript. This project is mostly based on material-datetime-picker, but without it relying on externa

Priyank Patel 51 Jul 18, 2022
Scrape tweets from Twitter search results based on keywords and date range using Playwright. Save scraped tweets in a CSV file for easy analysis

Tweet Harvest (Twitter Crawler) Tweet Harvest is a command-line tool that uses Playwright to scrape tweets from Twitter search results based on specif

Helmi Satria 33 Aug 9, 2023
Bootstrap Colorpicker is a modular color picker plugin for Bootstrap.

Bootstrap Colorpicker Bootstrap Colorpicker is a modular color picker plugin for Bootstrap 4. THIS PROJECT IS NOT MAINTAINED ANYMORE. After almost 10

Javi Aguilar 1.4k Dec 22, 2022
A super-lightweight, highly configurable, cross-browser date / time picker jQuery plugin

Zebra Datepicker A super-lightweight, highly configurable, cross-browser date/time picker jQuery plugin Zebra_Datepicker is a small yet and highly con

Stefan Gabos 391 Dec 29, 2022
A simplified jQuery date and time picker

jSunPicker A simplified jQuery date and time picker Why another Date picker? There are numerous date, time pickers out there. However, each of those l

null 1 May 31, 2022
this is a single-page web application. we built a book website where the user can add , remove and display books. we used modules to implement these functionalities. also, we used the Date class to display the date and time.

Awsome Books In this Project, we have built A Books websites. Built With ?? HTML CSS javascript Git & Github Live Demo Here you can find the live Demo

Nedjwa Bouraiou 10 Aug 3, 2022
Discard stdin input except for Ctrl+C

stdin-discarder Discard stdin input except for Ctrl+C This can be useful to prevent stdin input from interfering with stdout output. For example, you

Sindre Sorhus 13 Dec 17, 2022
A minimal typing practice website with no features except typing. Inspired from Monkeytype. Do ⭐ this repository.

SenpaiType Introduction SenpaiType is a minimal typing practice website with no features except typing. Inspired from Monkeytype. Contributing Raise i

Pruthviraj Jadhav 5 Nov 30, 2022
Beautiful UI-Range input component, highly customisable, based on CSS variables.

Beautiful UI-Range input component, highly customisable, based on CSS variables. including a floating output value, min & max values on the sides & ticks according to the steps

Yair Even Or 73 Dec 27, 2022
Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4.

Bootstrap Tooltip Custom Class Extends Bootstrap Tooltips and Popovers by adding custom classes. Available for Bootstrap 3 and Bootstrap 4. Define you

Andrei Victor Bulearca 14 Feb 10, 2022
A simple Form Validation Utility for Bootstrap 3, Bootstrap 4, and Bootstrap 5 for Humans.

bootstrap-validate A simple Form Validation Utility for Bootstrap 3, Bootstrap 4, and Bootstrap 5 for Humans. ?? Support us with Developer Merchandise

null 138 Jan 2, 2023
A jQuery Plug-in to select the time with a clock inspired by the Android time picker.

Clock Timepicker Plugin for jQuery See a demo here A free jQuery Plug-in to select the time with a clock inspired by the Android time picker. This plu

Andy 51 Dec 22, 2022
📆 The modern, open source "Airbnb style" date picker.

Date Picker A pretty, modern date picker. Coming soon. ?? Get Started wip wip ?? Testing pnpm test ?? Changelog Please see our releases page for more

Open Web Foundation 8 Oct 11, 2022
Flat and simple color-picker library. No dependencies, no jquery.

Flat and simple color-picker Fully Featured demo Features Simple: The interface is straight forward and easy to use. Practical: Multiple color represe

Ivan Matveev 15 Nov 14, 2022