如何在日期选择器中设置最大日期?

How to set max date in 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}
      />
    );
  }

这是我的代码

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

我正在尝试将最大日期设置在

之前 1 年

我不是使用 momment.js 的专家,但根据文档:https://momentjs.com/guides/#/lib-concepts/mutability/

也许您需要使用 .format()。我已经把它添加到你的 codesanbox 中了,它没有崩溃

您需要在 [minDate, maxDate] 区间内设置一个 initialDate

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

Demo

Source(不知道为什么他们的文档中没有提到这一点)。

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

此行将 return 恰好 365 天前的日期。

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;

要获得一个月后的日期,你可以使用这个

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