diff --git a/src/duration.ts b/src/duration.ts index 58492b2..c9488a9 100644 --- a/src/duration.ts +++ b/src/duration.ts @@ -181,8 +181,10 @@ export function roundToSingleUnit(duration: Duration, {relativeTo = Date.now()}: const daysDiff = Math.abs(Math.round((Number(newDate) - Number(relativeTo)) / 86400000)) + monthDateCorrection const monthsDiff = Math.abs(yearDiff * 12 + monthDiff) if (daysDiff < 27) { - if (days >= 6) { - weeks += Math.round(days / 7) + const roundedWeeks = Math.round(days / 7) + // Keep same-calendar-month spans as days instead of rounding 4 weeks to a month. + if (days >= 6 && (roundedWeeks < 4 || monthsDiff > 0)) { + weeks += roundedWeeks days = 0 } else { days = daysDiff diff --git a/test/duration.ts b/test/duration.ts index ecb9e68..b90f915 100644 --- a/test/duration.ts +++ b/test/duration.ts @@ -259,9 +259,9 @@ suite('duration', function () { ['-P21D', '-P3W', {relativeTo: new Date('2023-07-01T00:00:00')}], ['P24D', 'P3W', {relativeTo: new Date('2023-07-01T00:00:00')}], ['-P24D', '-P3W', {relativeTo: new Date('2023-07-01T00:00:00')}], - ['P24DT25H', 'P1M', {relativeTo: new Date('2023-07-01T00:00:00')}], + ['P24DT25H', 'P25D', {relativeTo: new Date('2023-07-01T00:00:00')}], ['-P24DT25H', '-P1M', {relativeTo: new Date('2023-07-01T00:00:00')}], - ['P25D', 'P1M', {relativeTo: new Date('2023-07-01T00:00:00')}], + ['P25D', 'P25D', {relativeTo: new Date('2023-07-01T00:00:00')}], ['-P25D', '-P1M', {relativeTo: new Date('2023-07-01T00:00:00')}], ['P1M1D', 'P1M', {relativeTo: new Date('2023-07-02T00:00:00')}], ['-P1M1D', '-P1M', {relativeTo: new Date('2023-07-02T00:00:00')}], @@ -365,6 +365,9 @@ suite('duration', function () { ['-P24D', [-3, 'week'], {relativeTo: '2023-01-01T00:00:00Z'}], ['P24DT25H', [1, 'month'], {relativeTo: '2023-01-15T00:00:00Z'}], ['P25D', [1, 'month'], {relativeTo: '2023-01-15T00:00:00Z'}], + ['P25D', [25, 'day'], {relativeTo: '2023-07-01T00:00:00Z'}], + ['-P25D', [-25, 'day'], {relativeTo: '2026-06-29T00:00:00Z'}], + ['-P26D', [-26, 'day'], {relativeTo: '2026-06-29T00:00:00Z'}], ['-P35D', [-1, 'month'], {relativeTo: '2023-02-07T22:22:57Z'}], ['-P45D', [-1, 'month'], {relativeTo: '2023-02-17T22:22:57Z'}], ['-P55D', [-1, 'month'], {relativeTo: '2023-02-27T22:22:57Z'}],