日期兩邊各一個月,然后陷入回圈。從 6 月開始,到 7 月底或 5 月初會順利進行,但隨后會回圈回到那幾個月的結束/開始,而不是更進一步。globalDate 是定義的 React 狀態const [globalDate, setGlobalDate] = useState(new Date());
代碼片段:
//decreasing
const newDate = new Date();
newDate.setDate(globalDate.getDate() - 1);
if (globalDate.getMonth() !== newDate.getMonth()) {
newDate.setMonth(globalDate.getMonth());
}
if (globalDate.getDate() <= 1) {
newDate.setMonth(globalDate.getMonth() - 1);
newDate.setDate(daysInMonth[newDate.getMonth()]);
}
setGlobalDate(newDate);
//increasing
const newDate = new Date();
newDate.setDate(globalDate.getDate() 1);
if (globalDate.getMonth() !== newDate.getMonth()) {
newDate.setMonth(globalDate.getMonth());
}
if (globalDate.getDate() >= daysInMonth[globalDate.getMonth()]) {
newDate.setMonth(globalDate.getMonth() 1);
newDate.setDate(1);
}
setGlobalDate(newDate);
整頁來源:https ://github.com/Westsi/thynkr/blob/master/frontend/web/js/src/Planner.js
uj5u.com熱心網友回復:
第一個代碼塊(“遞減”)中的問題發生在newDate.setMonth()當newDate日期是該月的最后一天并且上個月的天數較少時執行。因此,例如,它發生在newDate5 月 31 日,此時發出此呼叫setMonth。該呼叫會將日期調整為 4 月 31 日,但該日期會自動轉換為 5 月 1 日,因為 4 月只有 30 天,因此您會卡在 5 月。
為避免此類問題,請立即開始,globalDate減或加一天。就這樣。溢位到下/上個月是 JavaScript 已經自動處理的事情。因此,與其自己嘗試做這件事(并遇到麻煩),不如讓 JavaScript 為你做這件事:
遞減邏輯:
const newDate = new Date(globalDate); // starting point!
newDate.setDate(globalDate.getDate() - 1); // month overflow happens automatically!
setGlobalDate(newDate); // That's it!
增加邏輯:
const newDate = new Date(globalDate); // starting point!
newDate.setDate(globalDate.getDate() 1); // month overflow happens automatically!
setGlobalDate(newDate); // That's it!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496317.html
標籤:javascript 日期 约会时间
