edit | blame | history | raw

react-datetime

Build Status
npm version
npm

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.

Usage

Install using npm:
npm install --save react-datetime

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

Name Type Default Description
value Date new 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.
defaultValue Date new 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.
dateFormat boolean or string true Defines 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.
timeFormat boolean or string true Defines 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.
input boolean true Whether to show an input field to edit the date manually.
open boolean null Whether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside.
locale string null Manually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see i18n docs.
utc boolean false When true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
onChange function empty function Callback 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).
onFocus function empty function Callback trigger for when the user opens the datepicker.
onBlur function empty function Callback 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.
viewMode string or number 'days' The default view to display when the picker is shown ('years', 'months', 'days', 'time').
className string or string array '' Extra class name for the outermost markup element.
inputProps object undefined Defines additional attributes for the input element of the component. For example: placeholder, disabled, required and name.
isValidDate function () => true Define the dates that can be selected. The function receives (currentDate, selectedDate) and should return a true or false whether the currentDate is valid or not. See selectable dates.
renderDay function DOM.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 appearance customization.
renderMonth function DOM.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 appearance customization.
renderYear function DOM.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 appearance customization.
strictParsing boolean false Whether to use Moment.js's strict parsing when parsing input.
closeOnSelect boolean false When true, once the day has been selected, the datepicker will be automatically closed.
closeOnTab boolean true When true and the input is focused, pressing the tab key will close the datepicker.
timeConstraints object null Add 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.
disableOnClickOutside boolean false When true, keep the datepicker open when click event is triggered outside of component. When false, close it.

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.

var moment = 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 should be used by the instance.
js <Datetime locale="fr-ca" /> <Datetime locale="de" />
Here you can see the i18n example working.

Appearance customization

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.

var MyDTPicker = React.createClass({
    render: function(){
        return <Datetime
            renderDay={ 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.

Selectable dates

It is possible to disable dates in the calendar if the user are not allowed to select them. It is done using the prop isValidDate, which admits a function in the form function(currentDate, selectedDate) where both arguments are moment objects. The function should 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 component
var yesterday = Datetime.moment().subtract(1, 'day');
var valid = function( current ){
    return current.isAfter( yesterday );
};
<Datetime isValidDate={ valid } />

Working example of disabled days here.

It's also possible to disable the weekends, as shown in the example below.
js var valid = function( current ){ return current.day() !== 0 && current.day() !== 6; }; <Datetime isValidDate={ 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 * as Datetime  from 'react-datetime';

class MyDTPicker extends React.Component<MyDTPickerProps, MyDTPickerState> {
    render() JSX.Element {
        return <Datetime />;
    }
}

Contributions

Changelog

MIT Licensed

edit | blame | history | raw

Changelog

2.8.1

  • Fix timeFormat related bug where 'A' was being picked up but not 'a', for setting 12-hour clock.

2.8.0

  • Add typings for TypeScript 2.0. We now support TypeScript typings for versions 1.8 and 2.0.

2.7.5

  • Bumps the version to skip buggy deployment 2.7.4

2.7.4

  • Reverting updating react related dependencies. They were not the issue so they should not be set to the latest version of react.

2.7.3

  • When updating moment to 2.16.0 something broke, hopefully by updating all react prefixed dependencies to 15.4.0 and changing the syntax in the dependency object a bit will resolve this issue.

2.7.2

  • Bug fix: When setting locale and entering month view mode the component would sometimes freeze, depending on the locale. This has now been fixed.

2.7.1

  • Bug fix: onFocus and onBlur were being called in a way causing state to reset. This unwanted behavior is now adjusted.

2.7.0

  • isValidDate now supports months and years.
  • utc prop was added, by setting it to true input time values will be interpreted as UTC (Zulu time).
  • Bug fix: The input value now updates when dateFormat changes.
  • Removed the source-map file because the commit it was introduced in was causing the minified file to be bigger than the non-minified.

2.6.2

  • Update file references in package.json

2.6.1

  • Added a source-map file.
  • Fixed bug with invalid moment object.
  • Decreased npm package size by ~29.3KB.

2.6.0

  • Fixed hover styles for days
  • Added multiple simultaneous datetime component support.
  • className prop now supports string arrays
  • Fixes 12:00am
  • Removed warning for missing element keys.

2.5.0

  • Added pre-commit hook for tests.
  • Added the timeConstraints prop.

2.4.0

  • Added ES linting.
  • Added closeOnTab property.

2.3.3

  • Updated readme.
  • Fixed short months for not English locales.
  • Fixed mixed 12 AM/PM.

2.3.2

  • Time editor now handles the A format to display 12h times.

2.3.0

  • Added typescript definition file.
  • Changed button markup and updated styles.
  • Fixes autoclosing on time change.

2.2.1

  • Controlled datepicker now working for controlled datepickers

2.2.0

  • The picker can be used as a month or year picker just giving a format date without days/months
  • Updates test suite

2.1.0

  • Fixed rdtActive not getting set.
  • Add react-dom as external dependency.
  • Fixed rendering a span directly under the calendar table.
  • Added dev setup
  • Added example

2.0.2

  • Fixed january days go to november problem.

2.0.1

  • Fixed two days can't have the same header name.

2.0.0

  • DOM classes are now prefixed with rdt.
  • A modified version of OnClickOutside is now included in the code to handle react 0.13 and 0.14 versions.
  • Updated dependencies.

1.3.0

  • Added open prop.
  • Added strictParsing prop.
  • Fixed not possible to set value to ''.

1.2.1

  • Removed classlist-polyfill so the component can be used in the server side.

1.1.1

1.1.0

  • Datepicker can have an empty value. If the value in the input is not valid, onChange and onBlur will return input value.
  • onBlur is not triggered anymore if the calendar is not open.

1.0.0-rc.2

  • Added travis CI
  • Fixed not showing timepicker when dateFormat=false.

1.0.0-rc.1

This is the release candidate for this project. Now it is pretty usable and API won't change drastically in a while. If you were using the alpha versions (v0.x) there is a bunch of breaking changes:

  • date prop is now called defaultValue and it is the initial value to use the component uncontrolled.
  • value prop has been added to use it as a controlled component.
  • Removed minDate and maxDate props. Now to define what dates are valid it is possible to use the new isValidDate prop.
  • dateFormat and timeFormat default value is always the locale default format. In case that you don't want the component to show the date/time picker you should set dateFormat/timeFormat to false.

Moreover:
* Buttons doesn't submit anymore when the Datetime component is in a form.
* className prop has been added to customize component class.

edit | blame | history | raw

Contributing

:raised_hands::tada: First off, thanks for taking the time to contribute! :tada::raised_hands:

The following is a set of guidelines for contributing to react-datetime. The purpose of these guidelines is to maintain a high quality of code and traceability. Please respect these guidelines.

General

This repository use tests and a linter as automatic tools to maintain the quality of the code. These two tasks are run locally on your machine before every commit (as a pre-commit git hook), if any test fail or the linter gives an error you cannot create the commit. They are also run on a Travis CI machine when you create a pull request, and will not be merged unless Travis says all tests and the linting pass.

Git Commit Messages

  • Use the present tense ("Add feature" not "Added feature")
  • Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
  • Think of it as you are commanding what your commit is doing
  • Git itself uses the imperative whenever it creates a commit on your behalf, so it makes sense for you to use it too!
  • Use the body to explain what and why
  • If the commit is non-trivial, please provide more detailed information in the commit body message
  • How you made the change is visible in the code and is therefore very rarely necessary to include in the commit body message, but why you made the change is often harder to guess and should therefore be included in the commit body message

Here's a nice blog post about how to write great git messages - it's worth a read.

Pull Requests

  • Follow the current code style
  • Write tests for your changes
  • Add to documentation if it is needed
  • End files with a newline
  • There's no need to run npm build for each pull request, we do this when we release a new version
edit | blame | history | raw
The MIT License (MIT)

Copyright (c) 2014 Quri, Loïc CHOLLIER

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
.github/CONTRIBUTING 2 KB
.github/ISSUE_TEMPLATE 2 KB
.github/PULL_REQUEST_TEMPLATE 1 KB
CHANGELOG 7 KB
LICENSE 1 KB
README 14 KB
demo/README 521 b