我在我的專案中第一次使用 date-fns。我需要讓用戶能夠在當前日期添加一個月。我想知道這應該如何與不同長度的月份一起作業?
我嘗試了 30 天和 31 天的不同月份,但我無法理解。如果我在 2022 年 7 月 1 日加上一個月,我會得到 2022 年 7 月 31 日(我預計是 8 月 1 日),但如果我在 7 月 7 日加上一個月,我會得到 2022 年 8 月 7 日。
另外,我在 2023 年 2 月 15 日添加了一個月,得到的結果是 2023 年 3 月 14 日(預計 3 月 15 日)。然后,當我將一個月添加到 2023 年 2 月 1 日時,我得到 2023 年 3 月 1 日,這很好。
這是我的代碼:
export const addMonth(date, numOfMonths) {
return addMonths(Date.parse(date), numOfMonths)
// date is a date string
}
感謝有人可以提供建議。謝謝
uj5u.com熱心網友回復:
因為你沒有給出你所做的任何例子,所以不可能告訴你哪里出錯了一個快速的例子,使用你說不作業的日期
{
const start = new Date(2022, 6, 1);
const end = addMonths(start, 1);
console.log(`start ${start} add 1 months= ${end}`);
}
{
const start = new Date(2023, 1, 15);
const end = addMonths(start, 1);
console.log(`start ${start} add 1 months= ${end}`);
}
{
const start = new Date(2023, 1, 1);
const end = addMonths(start, 1);
console.log(`start ${start} add 1 months= ${end}`);
}
節目
start Fri Jul 01 2022 00:00:00 GMT 0100 (British Summer Time) add 1 months= Mon Aug 01 2022 00:00:00 GMT 0100 (British Summer Time)
start Wed Feb 15 2023 00:00:00 GMT 0000 (Greenwich Mean Time) add 1 months= Wed Mar 15 2023 00:00:00 GMT 0000 (Greenwich Mean Time)
start Wed Feb 01 2023 00:00:00 GMT 0000 (Greenwich Mean Time) add 1 months= Wed Mar 01 2023 00:00:00 GMT 0000 (Greenwich Mean Time)
所以一切都按預期作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/491295.html
標籤:javascript 日期 日期-fns
