How to disable past dates in material-ui Date picker? - material-ui

I'm using material-ui Date-Picker. How to disable past days before today's date?
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
function disablePastDays(date) {
//code here to disable past days
}
const calendar = () => (
<div>
<DatePicker shouldDisableDate={disablePastDays}/>
</div>
)

material-ui's DatePicker accepts minDate prop. So you might want this:
const today = new Date();
<DatePicker minDate={today}/>

Use disablePast.
<DatePicker
disablePast
/>
They have it since v1.0.0-beta.10.

We can give minDate as props to the DatePicker material UI component
Create a state using usestate and then pass the state value into the props as below
const [startMinDate, setStartDate] = useState(new Date())
<DatePicker
required
label="Date"
disablePast
minDate = {startMinDate}
/>

I am using import DatePicker from '#mui/lab/DatePicker'; library of version "#mui/lab": "^5.0.0-alpha.66"
Below code works fine for me
<DatePicker
disablePast
value={checkout.rideDate}
onChange={(newValue) => { // your code of onChange functionality}
/>
}
/>

Related

MUI Datepicker onChange event working with manual input but not when clicking date

I've been toying around with this for a while to no avail.
When the user inputs a date manually into the text field, that onChange event fires and everything works as I want it to. When the user clicks on a date from from datepicker, nothing at all happens.
I'm still getting used to using MUI fields in Controllers to suit React Hook Form, but I'm not sure what I'm doing incorrectly.
const { handleSubmit, control, register } = useForm();
const [selectedDate, setSelectedDate] = React.useState(null);
const handleDateChange = (date) => {
console.log(date)
setSelectedDate(date);
};
<form onSubmit={handleSubmit(submitForm)}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Controller
control={control}
name={"newEffectiveDate"}
defaultValue={null}
render={() => (
<KeyboardDatePicker
inputVariant="outlined"
disableToolbar
format="MM/dd/yyyy"
margin="normal"
id="date-picker-inline"
label="Date picker inline"
value={selectedDate}
onChange={date => handleDateChange(date)}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
)}
/>
</MuiPickersUtilsProvider>
</form>
Any help would be much appreciated!
Turns out, I just needed to add the autoOk prop to the KeyboardDatePicker component...

Configure Date Format of React Input Date-type

I have an <Input/> from reactstrap that accepts date. I'm using moment.js to parse my date. Although I want the format of the dates to be localized.
This is my code:
<Input
bsSize="lg"
type="date"
name="date"
value={moment(this.state.birthDate).locale('en').format("LLLL")}
onChange={this.handleBirthDateChange}
/>
Although when I try to select my date input, it doesn't accept the date chosen.
Moment will be an object, you'd need to format it to the ISO standard string which is the HTML's date type
Try this moment().format('YYYY-MM-DD')
Sandbox: https://codesandbox.io/s/musing-mclaren-tuqz0
This might help you get started
import React from 'react'
import ReactDOM from 'react-dom'
import moment from 'moment'
import {Input} from 'reactstrap'
import 'bootstrap/dist/css/bootstrap.css'
export class App extends React.Component {
constructor(props) {
super(props)
this.state = {
birthDate: moment()
.locale('en')
.format('YYYY-MM-DD')
}
}
handleChange = e => {
this.setState({birthDate: e.target.value})
}
render() {
let {birthDate} = this.state
return (
<>
<Input
bsSize="lg"
type="date"
name="date"
value={birthDate}
onChange={this.handleChange}
/>
</>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))

Material UI date picker Date format React

I can't see to format the Material UI Date picker in a React app??
When a user selects a date, I want it to format to be MM/DD/YYYY. I looked up a couple answers but it's not clear where the function to change the format is supposed to go??? For some reason, there is no clear function/location of where it goes online>>
DatePicker component
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
/**
* `DatePicker` can be implemented as a controlled input,
* where `value` is handled by state in the parent component.
*/
export default class DateSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
controlledDate: null,
openSnackbar: false,
snackbarText: {
dateconf: 'Date has been entered!'
}
};
}
formatDate(date){
return (date.getMonth() + 1) + "/" + date.getFullYear() + "/" + date.getDate();
}
handleChange = (event, date) => {
console.log('we are in a handle change in date select', event, date)
this.setState({
controlledDate: date,
});
// this.setState({
// openSnackbar: true
// })
};
render() {
console.log('state and props in date select', this.state, this.props)
return (
<DatePicker formatDate={this.formatDate}
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
);
}
}
///THE PARENT COMPONENT
handleDatePicker = (name, date) => {
console.log('handling date change', name, date)
this.setState(prevState => ({
currentRow: {
...prevState.currentRow,
purchase_date: date
},
purchase_date: date,
actionType: 'date'
}))
this.setState({
openSnackbar: true
})
}
<DateSelect
hintText="Purchase date"
value = {this.state.purchase_date}
onChange={this.handleDatePicker}
/>
You need to use formatDate function to format the date and time in date picker
formatDate --> This function is called to format the date displayed in the input field, and should return a string. By default
if no locale and DateTimeFormat is provided date objects are formatted
to ISO 8601 YYYY-MM-DD.
<DatePicker
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
formatDate={(date) => moment(new Date()).format('MM-DD-YYYY')}
/>
if you do not pass any format on the date it seems that the min and max date are not working.
For more details material-ui/DatePicker
Straight from the documentation of DatePicker. Try this
<DatePicker
inputFormat="MM/dd/yyyy"
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
inputFormat should usually do the trick. You can change it around the way you want and it can be used for dateTimePicker as well.
For example,
inputFormat="yyyy/MM/dd"
or any other way
formatDate did not work for me in V4. documention suggest inputFormat and worked properly.I found usage example here
<DatePicker
openTo="year"
views={["year", "month", "day"]}
value={toDate}
onChange={(newValue) => {setToDate(newValue);}}
maxDate={maxdate}
minDate={minDate}
format="DD-MM-YYYY"
/>

DatePicker date input with custom format

I want to stote dates in my state using redux-form. I use react-datepicker. To make the datepicker compatible with my redux-form i write:
import React, { PropTypes } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
const MyDatePicker = ({ input, meta: { touched, error } }) => (
<div>
<DatePicker
{...input} dateFormat="YYYY-MM-DD"
selected={input.value ? moment(input.value) : null}
/>
{
touched && error &&
<span className="error">
{error}
</span>
}
</div>
);
MyDatePicker.propTypes = {
input: PropTypes.shape().isRequired,
meta: PropTypes.shape().isRequired
};
export default MyDatePicker;
The problem is that when i choose date i want it to show as DD-MM-YYYY but i want the date to be saved in my state with the YYYY-MM-DD HH:MM:SS format. How to do this? I use the moment's format function but it did not seem to work
You should use the value lifecycle methods that redux-form provides for this.
Use parse to format the value coming from react-datepicker for storage and format to parse the value from the store back for react-datepicker to present it. Example:
function formatDateForInput(storedDate) {
// the returned value will be available as `input.value`
return moment(pickedDate).format('right format for your input')
}
function parseDateForStore(pickedDate) {
// the returned value will be stored in the redux store
return moment(storedDate).format('desired format for storage')
}
<Field
component={ MyDatePicker }
format={ formatDateForInput }
parse={ parseDateForStore }
/>
If this does not work for your, I would recommend checking if you need to put a custom onChange handler between the DatePicker and input prop provided by redux-form. Because it could be that the values DatePicker is using to call onChange are ones that redux-form does not understand. Like this:
const MyDatePicker = ({ input, meta: { touched, error } }) => {
const onChange = event => {
const pickedDate = event.path.to.value;
input.onChange(pickedDate);
}
return (
<div>
<DatePicker
dateFormat="YYYY-MM-DD"
selected={input.value ? moment(input.value) : null}
onChange={ onChange }
/>
{
touched && error &&
<span className="error">
{error}
</span>
}
</div>
);
}
MyDatePicker.propTypes = {
input: PropTypes.shape().isRequired,
meta: PropTypes.shape().isRequired
};
export default MyDatePicker;
Hope this helps!
If i am understanding correct you just need 2 different formats for same date one on UI and other to save ? moment(date).format('DD-MM-YYYY') and moment(date).format('YYYY-MM-DD HH:MM:SS') will give you both formats date.
Just use the prop dateFormat="dd/MM/yyyy"
Example :
<DatePicker
selected={startDate}
onChange={date => handleChange(date)}
dateFormat="DD/MM/YYYY"
/>
I used the below props -mask, inputFormat and format - to change the default format to "yyyy-MM-dd" format.
The format code "yyyy-MM-dd" is important, play around this to find the desired format.
Example:
<LocalizationProvider dateAdapter={AdapterDateFns} >
<DatePicker
label="SomeDate"
{...register("details_received_date")}
mask="____-__-__"
inputFormat="yyyy-MM-dd"
format="yyyy-MM-dd"
value={someDate}
onChange={(newValue) => {setSomeDate(newValue);}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
This will display in the front end and provide the value as well in the desired format.
Hope this helps.
Try this
inputFormat="DD/MM/YYYY"
const [value, setValue] = useState(null);
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="DatePicker Example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
inputFormat="DD/MM/YYYY"
/>
</LocalizationProvider>

Disable previous Dates in ajaxToolkit CalendarExtender

How to disable previous dates while using in ajaxToolkit CalendarExtender
One Option is to use a rangevalidator on the textbox the calenderextender is bound to. Ie if you have the TargetID of the calendar extender set to tb1 add a rangeValidator to flag when the contents of tb1 is before today.
Another option is using javascript and here is a good example:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=149 TIP 6.
Here is my full solution to the calendar date restriction problem: What I like about this solution is that you set the MinimumValue and MaximumValue of a RangeValidator and you do not have to modify any javascript. I never found a full solution that did not require recompiling the AjaxControlToolkit.dll. Thanks to http://www.karpach.com/ajaxtoolkit-calendar-extender-tweaks.htm for giving me the idea of how to override key methods in the calendar.js file without having to recompile the AjaxControlToolkit.dll. Also, I got "AjaxControlToolkit is undefined" javascript errors, so I changed those to Sys.Extended.UI. and it works for me when using the 4.0 version of the toolkit.
<%--//ADD THIS NEW STYLE TO STYLESHEET TO GRAY OUT DATES THAT AREN'T SELECTABLE--%>
<style type="text/css">
.ajax__calendar_inactive {color:#dddddd;}
</style>
Either in Page_Load or Init or wherever, set the min and max values for your range validator:
<script runat="server">
protected override void OnLoad(EventArgs e)
{
//set the validator min and max values
this.valDateMustBeWithinMinMaxRange.MinimumValue = DateTime.Today.Date.ToShortDateString();
this.valDateMustBeWithinMinMaxRange.MaximumValue = DateTime.MaxValue.Date.ToShortDateString();
base.OnLoad(e);
}
</script>
Add this javascript somewhere in your page:
<script type="text/javascript">
<%--// ADD DATE RANGE FEATURE JAVASCRIPT TO OVERRIDE CALENDAR.JS--%>
var minDate = new Date('<%= valDateMustBeWithinMinMaxRange.MinimumValue %>');
var maxDate = new Date('<%= valDateMustBeWithinMinMaxRange.MaximumValue %>');
Sys.Extended.UI.CalendarBehavior.prototype._button_onblur_original = Sys.Extended.UI.CalendarBehavior.prototype._button_onblur;
//override the blur event so calendar doesn't close
Sys.Extended.UI.CalendarBehavior.prototype._button_onblur = function (e) {
if (!this._selectedDateChanging) {
this._button_onblur_original(e);
}
}
Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick_original = Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick;
//override the click event
Sys.Extended.UI.CalendarBehavior.prototype._cell_onclick = function (e) {
var selectedDate = e.target.date;
if (selectedDate < minDate || selectedDate > maxDate ) {
//alert('Do nothing. You can\'t choose that date.');
this._selectedDateChanging = false;
return;
}
this._cell_onclick_original(e);
}
Sys.Extended.UI.CalendarBehavior.prototype._getCssClass_original = Sys.Extended.UI.CalendarBehavior.prototype._getCssClass;
Sys.Extended.UI.CalendarBehavior.prototype._getCssClass = function (date, part) {
var selectedDate = date;
if (selectedDate < minDate || selectedDate > maxDate ) {
return "ajax__calendar_inactive";
}
this._getCssClass_original(date, part);
}
</script>
Add this text box to your asp.net page with CalendarExtenter and RangeValidator:
<asp:TextBox ID="textBoxDate" runat="server" />
<ajaxToolkit:CalendarExtender ID="calendarExtender" runat="server" TargetControlID="textBoxDate" />
<asp:RangeValidator ID="valDateMustBeWithinMinMaxRange" runat="server" ControlToValidate="textBoxDate"
ErrorMessage="The date you chose is not in accepted range" Type="Date" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
Using the Ajax toolkit Calendar Extender in the html markup:
<asp:TextBox ID="txtDate" runat="server" CssClass="contentfield" Height="16px" MaxLength="12" width="80px" Wrap="False"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender3" runat="server" Enabled="true" StartDate="<%# DateTime.Now %>" EndDate="<%# DateTime.Now.AddDays(1) %>" Format="dd MMM yyyy" PopupButtonID="imgDatePicker" TargetControlID="txtDate">
</asp:CalendarExtender>
<asp:ImageButton ID="imgDatePicker" runat="Server" AlternateText="Click to show calendar" Height="16px" ImageAlign="Middle" ImageUrl="~/images/Calendar_scheduleHS.png" Width="16px" />
Above you will see that the Calendar only allows one to choose between today or tomorrow by setting
StartDate="<%# DateTime.Now %>"
and
EndDate="<%# DateTime.Now.AddDays(1) %>"
This can also be done in the backend using CalendarExtender1.StartDate = DateTime.Now; or CalendarExtender1.EndDate = DateTime.Now.AddDays(1);
Just add an attribute StartDate="<%# DateTime.Now %>" in you ajaxtoolkit calendarextender control
Following link might help you:
Disable dates in CalendarExtender