Reputation:
How can I set Minimum Date, so the user can't pick To Date that is before From Date.
Here is my Two Date Pickers, using moment
to format the date.
<DatePicker
value={fromDate}
label="From Date"
color="primary"
inputFormat="DD/MM/YYYY"
onChange={(fromDateValue) =>
setFromDate(moment(fromDateValue).format('DD-MMM-YYYY', moment.ISO_8601))
}
renderInput={(params) => <TextField {...params} size="small" margin="dense" sx={{ width: 238 }} />}
/>
<DatePicker
value={toDate}
label="To Date"
color="primary"
inputFormat="DD/MM/YYYY"
onChange={(toDateValue) => setToDate(moment(toDateValue).format('DD-MMM-YYYY', moment.ISO_8601))}
renderInput={(params) => (
<TextField {...params} size="small" margin="dense" sx={{ width: 218 }} color="primary" />
)}
/>
Upvotes: 2
Views: 10185
Reputation: 1012
import { givenDateAndCurrentTime } from "date-fran";
const stringdate = `${year}-${month}-${day}`
<DatePicker
format="dd/MM/yyyy"
minDate={givenDateAndCurrentTime(stringdate)}
value={props.values[props.fieldName]}
label="Arrival date"
/>
Upvotes: 0
Reputation: 63
const currentDate = new Date();
const minDate = currentDate; // Current date
const maxDate = addDays(currentDate, 30); // max date (30+ days)
const dateObj = new Date(minDate);
const year = dateObj.getFullYear();
const month = String(dateObj.getMonth() + 1).padStart(2, "0");
const day = String(dateObj.getDate()).padStart(2, "0");
const formattedDate = `${year}-${month}-${day}`;
const dateObj1 = new Date(maxDate);
const year1 = dateObj1.getFullYear();
const month1 = String(dateObj1.getMonth() + 1).padStart(2, "0");
const day1 = String(dateObj1.getDate()).padStart(2, "0");
const formattedDate1 = `${year1}-${month1}-${day1}`;
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DemoContainer components={["DatePicker"]}>
<DatePicker
label="Date"
sx={{
backgroundColor: "rgba(255, 255, 255, 0.30)",
borderRadius: 2,
border: "1px solid",
borderColor:
showError && !selectedDate ? "red" : "initial",
}}
showDaysOutsideCurrentMonth
value={selectedDate}
onChange={handleDateChange}
minDate={dayjs(formattedDate)}
maxDate={dayjs(formattedDate1)}
/>
</DemoContainer>
</LocalizationProvider>
Upvotes: 0