簡體   English   中英

如何在日期選擇器中設置最大日期?

[英]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 年前

您需要在 [minDate, maxDate] 間隔內設置一個initialDate

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

演示

來源(不知道為什么他們的文檔中沒有提到這一點)。

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

此行將返回正好 365 天前的日期。

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

也許您需要使用.format() 我已將其添加到您的代碼框中並且它不會崩潰

如果您設置的范圍為 1 年,您可以執行以下操作,示例

<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;

要在一個月后獲取日期,您可以使用它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM