我想顯示兩個日期時間之間的持續時間,但我發現了一個我不確定為什么它不起作用的案例。我目前正在使用date-fns,我也嘗試過luxon,它給了我相同的結果。
代碼片段
import { intervalToDuration as intervalToDurationDateFns } from 'date-fns';
import { DateTime } from "luxon";
function intervalToDurationLuxon({ start, end }) {
const startDate = DateTime.fromJSDate(start);
const endDate = DateTime.fromJSDate(end);
const i = startDate.until(endDate);
return i.toDuration(['years', 'months', 'days', 'hours', 'minutes', 'seconds']).toObject();
}
const target = new Date(2023, 2, 1, 23, 59, 59, 999);
const beforeMiddleOfNight = new Date(2022, 8, 29, 23, 59, 59, 99);
const afterMiddleOfNight = new Date(2022, 8, 30, 0, 0, 0, 0);
console.log('date-fns')
console.log(intervalToDurationDateFns({ start: beforeMiddleOfNight, end: target }));
console.log(intervalToDurationDateFns({ start: afterMiddleOfNight, end: target }));
console.log('luxon')
console.log(intervalToDurationLuxon({ start: beforeMiddleOfNight, end: target }));
console.log(intervalToDurationLuxon({ start: afterMiddleOfNight, end: target }));
實際輸出
date-fns
{years: 0, months: 5, days: 1, hours: 0, minutes: 0, seconds: 0}
{years: 0, months: 5, days: 1, hours: 23, minutes: 59, seconds: 59}
luxon
{years: 0, months: 5, days: 1, hours: 0, minutes: 0, seconds: 0.9}
{years: 0, months: 5, days: 1, hours: 23, minutes: 59, seconds: 59.999}
預期產出
date-fns
{years: 0, months: 5, days: 2, hours: 0, minutes: 0, seconds: 0}
{years: 0, months: 5, days: 1, hours: 23, minutes: 59, seconds: 59}
luxon
{years: 0, months: 5, days: 2, hours: 0, minutes: 0, seconds: 0.9}
{years: 0, months: 5, days: 1, hours: 23, minutes: 59, seconds: 59.999}
我發現這只發生在一個月start的最后一天(28、29、30 或 31)并且在3 月1 日和3 月 28日之間。我注意到的另一件事是一天中的時間無關緊要(與年份相同),它仍然給出錯誤的輸出。end
我不明白為什么在這種情況下錯誤地計算了天數。
有人可以解釋一下為什么會這樣嗎?
是否有更好的解決方案可以涵蓋我找不到的其他場景?
uj5u.com熱心網友回復:
僅當開始是一個月的最后一天(28、29、30 或 31)并且結束在 3 月 1 日和 3 月 28 日之間時才會發生這種情況。
原因是二月只有28天,月數不準確。
當您在月底(28 日、29 日、30 日或 31 日)并添加幾個月以便您在 2 月到達時,您總是會在2 月 28 日結束。以月計,所有這些間隔都具有相同的持續時間,無論它們從哪一天開始。然后,“余數”被計算為您必須添加到 2 月 28 日才能在 3 月到達所需日期時間的天數、小時數等。
這不僅發生在 3 月結束的間隔中,而且適用于所有月份:如果結束日期的日期小于月份的開始日期,但開始日期的日期大于月份的數量結束日期前一個月的天數,多余的天數將被忽略。
另請參閱有關math的檔案Duration。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513113.html
下一篇:這是哪種日期格式?
