Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - pasonatquila/react-datetime: A lightweight but complete datetime picker react component. · GitHub
Skip to content

Repository files navigation

react-datetime

Build Statusnpm version

A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is highly customizable and it even allows to edit date's milliseconds.

This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.

Installation

Install using npm:

npm install --save react-datetime

Install using yarn:

yarn add react-datetime

Usage

React.js and Moment.js are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.

require('react-datetime');
...
render: function(){return<Datetime/>;}

See this example working.

Don't forget to add the CSS stylesheet to make it work out of the box.

API

NameTypeDefaultDescription
valueDatenew Date()Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
defaultValueDatenew Date()Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by Moment.js, so it is possible to use a date string or a moment object.
dateFormatboolean or stringtrueDefines the format for the date. It accepts any Moment.js date format (not in localized format). If true the date will be displayed using the defaults for the current locale. If false the datepicker is disabled and the component can be used as timepicker, see available units docs.
timeFormatboolean or stringtrueDefines the format for the time. It accepts any Moment.js time format (not in localized format). If true the time will be displayed using the defaults for the current locale. If false the timepicker is disabled and the component can be used as datepicker, see available units docs.
inputbooleantrueWhether to show an input field to edit the date manually.
openbooleannullWhether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
localestringnullManually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utcbooleanfalseWhen true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChangefunctionempty functionCallback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).
onFocusfunctionempty functionCallback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent.
onBlurfunctionempty functionCallback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returned.
onViewModeChangefunctionempty functionCallback trigger when the view mode changes. The callback receives the selected view mode string (years, months, days or time) as only parameter.
viewModestring or number'days'The default view to display when the picker is shown ('years', 'months', 'days', 'time').
classNamestring or string array''Extra class name for the outermost markup element.
inputPropsobjectundefinedDefines additional attributes for the input element of the component. For example: onClick, placeholder, disabled, required, name and className (classNamesets the class attribute for the input element). See Customize the Input Appearance.
renderInputfunctionundefinedReplace the rendering of the input element. The accepted function has openCalendar (a function which opens the calendar) and the default calculated props for the input. Must return a React component or null. See Customize the Input Appearance.
isValidDatefunction() => trueDefine the dates that can be selected. The function receives (currentDate, selectedDate) and shall return a true or false whether the currentDate is valid or not. See selectable dates.
renderDayfunctionDOM.td(day)Customize the way that the days are shown in the daypicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, and must return a React component. See Customize the Datepicker Appearance.
renderMonthfunctionDOM.td(month)Customize the way that the months are shown in the monthpicker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the month and the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
renderYearfunctionDOM.td(year)Customize the way that the years are shown in the year picker. The accepted function has the selectedDate, the current date and the default calculated props for the cell, the year to be shown, and must return a React component. See Customize the Datepicker Appearance.
strictParsingbooleanfalseWhether to use Moment.js's strict parsing when parsing input.
closeOnSelectbooleanfalseWhen true, once the day has been selected, the datepicker will be automatically closed.
closeOnTabbooleantrueWhen true and the input is focused, pressing the tab key will close the datepicker.
timeConstraintsobjectnullAdd some constraints to the timepicker. It accepts an object with the format { hours: { min: 9, max: 15, step: 2 }}, this example means the hours can't be lower than 9 and higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the hours, minutes, seconds and milliseconds.
disableOnClickOutsidebooleanfalseWhen true, keep the datepicker open when click event is triggered outside of component. When false, close it.
formatYearMonthfunctionnullDefines the format for the year-month in the daypicker.
formatYearfunctionnullDefines the format for the year in the monthpicker.
formatYearsfunctionnullDefines the format for the years in the yearpicker.

i18n

Different language and date formats are supported by react-datetime. React uses Moment.js to format the dates, and the easiest way of changing the language of the calendar is changing the Moment.js locale.

varmoment=require('moment');require('moment/locale/fr');// Now react-datetime will be in french

If there are multiple locales loaded, you can use the prop locale to define what language shall be used by the instance.

<Datetimelocale="fr-ca"/><Datetimelocale="de"/>

Here you can see the i18n example working.

Customize the Input Appearance

It is possible to customize the way that the input is displayed. The simplest is to supply inputProps which get assigned to the default <input /> element within the component.

<DateTimeinputProps={{placeholder: 'N/A',disabled: true}}>

Alternatively, if you need to render different content than an <input /> element, you may supply a renderInput function which is called instead.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderInput={this.renderInput}/>;},renderInput: function(props,openCalendar){functionclear(){props.onChange({target: {value: ''}});}return(<div><input{...props}/><buttononClick={openCalendar}>open calendar</button><buttononClick={clear}>clear</button></div>);},});

Customize the Datepicker Appearance

It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props renderDay(props, currentDate, selectedDate), renderMonth(props, month, year, selectedDate) and renderYear(props, year, selectedDate) to customize the output of each rendering method.

varMyDTPicker=React.createClass({render: function(){return<DatetimerenderDay={this.renderDay}renderMonth={this.renderMonth}renderYear={this.renderYear}/>;},renderDay: function(props,currentDate,selectedDate){return<td{...props}>{'0'+currentDate.date()}</td>;},renderMonth: function(props,month,year,selectedDate){return<td{...props}>{month}</td>;},renderYear: function(props,year,selectedDate){return<td{...props}>{year%100}</td>;}});

You can see a customized calendar here.

Method Parameters

  • props is the object that the datepicker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its className attribute is used by the default styles.
  • selectedDate and currentDate are moment objects and can be used to change the output depending on the selected date, or the date for the current day.
  • month and year are the numeric representation of the current month and year to be displayed. Notice that the possible month values range from 0 to 11.

Specify Available Units

You can filter out what you want the user to be able to pick by using dateFormat and timeFormat, e.g. to create a timepicker, yearpicker etc.

In this example the component is being used as a timepicker and can only be used for selecting a time.

<DatetimedateFormat={false}/>

Working example of a timepicker here.

In this example you can only select a year and month.

<DatetimedateFormat="YYYY-MM"timeFormat={false}/>

Working example of only selecting year and month here.

Selectable Dates

It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function shall return true for selectable dates, and false for disabled ones.

In the example below are all dates before today disabled.

// Let's use the static moment reference in the Datetime componentvaryesterday=Datetime.moment().subtract(1,'day');varvalid=function(current){returncurrent.isAfter(yesterday);};<DatetimeisValidDate={valid}/>

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.

varvalid=function(current){returncurrent.day()!==0&&current.day()!==6;};<DatetimeisValidDate={valid}/>

Working example of disabled weekends here.

Usage with TypeScript

This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not required.

Typings for 1.8 are found in react-datetime.d.ts and typings for 2.0 are found in typings/index.d.ts.

import*asDatetimefrom'react-datetime';classMyDTPickerextendsReact.Component<MyDTPickerProps,MyDTPickerState>{render()JSX.Element{return<Datetime/>;}}

Contributions

For information about how to contribute, see the CONTRIBUTING file.

Development

npm run dev

This will start a local webpack-dev-server based on example/example.js where most development can be done.

If you want to develop using the component inside a React application, we recommend that you use react-datetime-playground.

About

A lightweight but complete datetime picker react component.

Resources

Contributing

Stars

0 stars

Watchers

4 watching

Forks

Releases

Packages

Contributors

Languages