简体   繁体   English

需要使用 Reactjs 从 startDate 开始执行 endDate 不能超过一年

[英]Need to implement endDate cannot be more than one year from startDate using Reactjs

Hi I need to implement the end date cannot be more than one year from start date using ReactJs.嗨,我需要使用 ReactJs 实施结束日期不能超过一年的开始日期。 The dates are being input as textfield, masked as date.日期作为文本字段输入,掩蔽为日期。 Here is the code to accept start and end dates from UI这是从 UI 接受开始和结束日期的代码

You can use the moment library to make things easier.您可以使用moment库使事情变得更容易。 But in plain Javascript, if you can manage to get a Date object from both your textfields:但是在普通的 Javascript 中,如果您可以设法从两个文本字段中获取Date object:

const getNumberOfDaysSinceEpoch = (numberOfSecondsSinceEpoch) => {
    return numberOfSecondsSinceEpoch/60/60/24;
}

const dateFromInDays = getNumberOfDaysSinceEpoch(dateFromObj.getTime());
const dateToInDays = getNumberOfDaysSinceEpoch(dateToObj.getTime())
if(dateToInDays - dateFromInDays > 365) {
   //it has been more than a year
}

where dateFromObj and dateToObj are the Date objects that I mentioned above.其中dateFromObjdateToObj是我上面提到的Date对象。

You can use getFullYear(), getMonth() and getDate() methods of Date object.您可以使用日期 object 的 getFullYear()、getMonth() 和 getDate() 方法。 Or simply calculate distance between two dates using "-" operator.或者简单地使用“-”运算符计算两个日期之间的距离。

const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");

const endDateChange = (evt) => {
    const _date = new Date(evt.target.value);
    const _startDate = new Date(startDate);
    // or try your date conversion
    const diffTime = Math.abs(_date - _startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
    if (diffDays > 365) {
        console.log ("more than 1 year");
        // set manually limit date string
        _startDate.setFullYear(_startDate.getFullYear() + 1);
        // assume you converted date to string named strLimitDate

        setEndDate(strLimitDate);
    } else {
        setEndDate(evt.target.value);
    }
}

return(
    <TextField... value={startDate} onChange={startDateChange} />
    <TextField ... value={endDate} onChange={endDateChange} />
)

You need to try on child component of Field.您需要尝试使用 Field 的子组件。 So in your case, TextField would be correct所以在你的情况下, TextField 是正确的

Finally I have used最后我用过

moment(endDate).diff(startdate, 'years',true) > 1

true is being used to consider decimal values. true 用于考虑十进制值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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