我有這個柏樹測驗,我在其中檢查正確的計費日期。我們的網站有每月訂閱,它的作業方式如下:如果您在 1 月 31 日開始訂閱,您的下一個結算日期將自動在 3 月 1 日,因為 2 月只有 28 天。同樣,如果您在 3 月 31 日開始訂閱,那么您的下一個計費日期將是 5 月 1 日,因為 4 月沒有 31 日,并且它會自動更改為下個月的第一天。從其他正常日期(如 15 日)開始將始終是下個月的同一日期(15 日)等。
我的問題是用柏樹測驗這個時,我總是得到下個月的最后一天。例如,如果我測驗我將在 3 月 31 日開始訂閱,我的測驗將 4 月 30 日作為預期結果,這是不正確的,因為我希望我的測驗的預期結果是 5 月 1 日。
我正在使用此功能,但我似乎無法使其正常作業,因為這幾個月有很多差異。
export const getBillingDate = (todayDate: string, months: number) => {
const date1 = new Date(todayDate)
const date2 = new Date(todayDate)
date1.setDate(1)
const daysInNextMonth = getDaysInMonth(addMonths(date1, months))
date2.setDate(Math.min(date2.getDate(), daysInNextMonth))
return format(addMonths(date2, months), 'MMMM do, yyyy')
}
我真的很感謝任何人對此的幫助,因為我是賽普拉斯的新手并且通常進行測驗。(抱歉英語不是我的母語)
uj5u.com熱心網友回復:
dayjs和 javascript都new Date()無法完全按照您的需要添加所有日期。
但是您可以使用dayjs().daysInMonth()完全按照您的描述獲得結果,
const getBilling = (startDate) => {
const [year, month, day] = startDate.split('/')
const sd = dayjs(startDate)
const firstOfNextMonth = sd.month(sd.month() 1).date(1)
const daysInNextMonth = dayjs(firstOfNextMonth).daysInMonth()
let end;
if (daysInNextMonth < day) {
end = `${year}/${ month 2}/${1}` // always bump to 1st day of month 2
} else {
end = `${year}/${ month 1}/${day}`
}
return dayjs(end, 'YYYY/MM/DD').format('YYYY/MM/DD')
}
it('gets billing date, accounting for short months', () => {
//Jan
expect(getBilling('2022/01/15')).to.eq('2022/02/15')
expect(getBilling('2022/01/31')).to.eq('2022/03/01')
//Feb
expect(getBilling('2022/02/15')).to.eq('2022/03/15')
expect(getBilling('2022/02/28')).to.eq('2022/03/28')
//Mar
expect(getBilling('2022/03/15')).to.eq('2022/04/15')
expect(getBilling('2022/03/31')).to.eq('2022/05/01')
})

uj5u.com熱心網友回復:
Day.js已經存在做日期數學。
您可以使用它們.add()為日期添加 30 天dayjs().add(30, 'day')。
您還可以格式化日期.format()以格式化您想要的方式dayjs('2019-01-25').format('DD/MM/YYYY') // '25/01/2019'
uj5u.com熱心網友回復:
你的要求有點不尋常。通常,當添加一個月并溢位時,要求是回傳該月的最后一天,而不是下個月的第一天。但這并不難,只需獲取開始日期(月份中的某天),加上一個月,如果結果日期不一樣,則將其設定為第一個,例如:
function addBillingMonth(date = new Date()) {
let d = new Date( date);
let dayNum = d.getDate();
d.setMonth(d.getMonth() 1);
if (dayNum !== d.getDate()) {
d.setDate(1);
}
return d;
}
// Examples
[ new Date(2021,11,31), // 31 Dec
new Date(2022, 0,15), // 15 Jan
new Date(2022, 0,31), // 31 Jan
new Date(2022, 2,31), // 31 Mar
].forEach(d => console.log(d.toDateString()
' next bill: ' addBillingMonth(d).toDateString())
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453937.html
標籤:javascript 约会时间 测试 柏
上一篇:對嵌套在陣列中的結構元素進行排序
