簡體   English   中英

使用 KeyboardDatePicker 的 React.js 中兩個日期之間的月差

[英]Difference in Months between two dates in React.js using KeyboardDatePicker


const Index = (props) => {

    const [selectedDate, setSelectedDate] = useState(
        new Date("2014-08-18T21:11:54")
      );
    
      const handleDateChange = (date) => {
        setSelectedDate(date);
      };
return (
<div>
//first date picker
 <MuiPickersUtilsProvider
                    utils={DateFnsUtils}
                    //  className={classes.formControlNew}

                    style={{ width: "100%" }}
                  >
                    <KeyboardDatePicker
                      style={{ marginLeft: "5%", width: "91%" }}
                      margin="normal"
                      id="date-picker-dialog1"
                      label="Start Date"
                      format="MM/dd/yyyy"
                      value={selectedDate}
                      onChange={handleDateChange}
                      KeyboardButtonProps={{
                        "aria-label": "change date",
                      }}
                    />
                  </MuiPickersUtilsProvider>

// second date picker

 <MuiPickersUtilsProvider
                    utils={DateFnsUtils}
                    
                    style={{ width: "100%" }}
                  >
                    <KeyboardDatePicker
                      style={{ marginLeft: "5%", width: "91%" }}
                      margin="normal"
                      id="date-picker-dialog2"
                      label="End Date"
                      format="MM/dd/yyyy"
                      value={selectedDate}
                      onChange={handleDateChange}
                      KeyboardButtonProps={{
                        "aria-label": "change date",
                      }}
                    />
                  </MuiPickersUtilsProvider>
</div>
);
};

我使用兩個日期選擇器從用戶那里獲取兩個日期。其中第一個日期是開始日期,第二個是結束日期。 我想計算這兩個日期之間的月差。我應該如何得到月差? Reactjs中需要做哪些計算。

這里缺少一些東西。

  1. 您將要復制selectedDatehandleDateChange以便您可以分別跟蹤這兩個日期。 也許selectedStartDateselectedEndDate

  2. 要計算差異,我建議使用moment npm package 語法類似於:

const months = moment.duration(moment(selectedEndDate).diff(moment(selectedStartDate))).asMinutes()

暫無
暫無

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

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