简体   繁体   中英

How to set max date in date picker?

I am trying to set max date in date picker getting error this

I am using this date picker https://www.npmjs.com/package/semantic-ui-calendar-react

render() {
    return (
      <DateInput
        name="date"
        placeholder="Date"
        // this works
        // maxDate={moment()}
       // this is not working
        maxDate={moment().subtract(1,'years')}
        value={this.state.date}
        iconPosition="left"
        onChange={this.handleChange}
      />
    );
  }

here is my code

https://codesandbox.io/s/semantic-ui-example-v9v03

I am trying to set max date 1 year before

You need to set an initialDate inside [minDate, maxDate] interval.

<DateInput
  maxDate={moment().subtract(1, "years")}
  initialDate={moment().subtract(1, "years")} <==
  value={this.state.date}
/>

Demo

Source (not sure why this isn't mentioned on their documentation).

new Date(new Date().setDate(new Date().getDate()-365))

This line will return the date from exactly 365 days ago.

I'm not an expert using momment.js but according the docs: https://momentjs.com/guides/#/lib-concepts/mutability/

maybe you need to use .format() . I've added it in your codesanbox and it doesn't crash

If you're setting a range of 1 year you could do the following, sample :

<DateInput
    maxDate={moment()}
    minDate={moment().subtract(1, "y")}
    value={this.state.date}
/>
Hello please below example:

import React from "react";

import { DateInput } from "semantic-ui-calendar-react";

const currentdate = new Date();
const currentYear = currentdate.getFullYear();
const maxdate = new Date(currentdate.setYear(currentdate.getFullYear() + 1));
class DateTimeForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      date: "",
      time: "",
      dateTime: "",
      datesRange: ""
    };
  }

  handleChange = (event, { name, value }) => {
    if (this.state.hasOwnProperty(name)) {
      this.setState({ [name]: value });
    }
  };

  render() {
    return (
      <DateInput
        dateFormat="DD - MM - YYYY"
        name="date"
        placeholder="Date"
        maxDate={maxdate}
        value={this.state.date}
        iconPosition="left"
        onChange={this.handleChange}
      />
    );
  }
}
export default DateTimeForm;

To get date after one month you can use this

 const currentDate = new Date()
  const calculateValidDate = new Date(currentDate.setMonth(currentDate.getMonth() + 1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM