diff --git a/src/duration.ts b/src/duration.ts index eb41a53c..0195fc20 100644 --- a/src/duration.ts +++ b/src/duration.ts @@ -156,7 +156,7 @@ export function elapsedTime(date: Date, precision: Unit = 'second', now = Date.n const day = Math.floor(hr / 24) const month = Math.floor(day / 30) const year = Math.floor(month / 12) - const i = unitNames.indexOf(precision) || unitNames.length + const i = unitNames.indexOf(precision) return new Duration( i >= 0 ? year * sign : 0, i >= 1 ? (month - year * 12) * sign : 0, diff --git a/test/duration.ts b/test/duration.ts index 95968531..87707de1 100644 --- a/test/duration.ts +++ b/test/duration.ts @@ -1,5 +1,6 @@ import {assert} from '@open-wc/testing' import {applyDuration, Duration, elapsedTime, getRelativeTimeUnit, roundToSingleUnit} from '../src/duration.ts' +import type {Unit} from '../src/duration.ts' import type {DurationFormatOptions} from '../src/duration-format-ponyfill.ts' import {Temporal} from '@js-temporal/polyfill' @@ -224,6 +225,24 @@ suite('duration', function () { input: '2023-03-21T16:03:00.000Z', expected: '-P1DT20H', }, + { + now: '2022-10-24T14:46:00.000Z', + input: '2024-10-24T14:46:00.000Z', + precision: 'year', + expected: 'P2Y', + }, + { + now: '2022-10-24T14:46:00.000Z', + input: '2020-10-24T14:46:00.000Z', + precision: 'year', + expected: '-P2Y', + }, + { + now: '2022-10-24T14:46:00.000Z', + input: '2024-10-24T14:46:00.000Z', + precision: 'unknown' as Unit, + expected: 'PT0S', + }, ]) for (const {input, now, precision = 'millisecond', expected} of elapsed) { test(`${input} is ${expected} elapsed from ${now} (precision ${precision})`, () => { diff --git a/test/relative-time.js b/test/relative-time.js index 307ba594..59b658b4 100644 --- a/test/relative-time.js +++ b/test/relative-time.js @@ -1561,6 +1561,12 @@ suite('relative-time', function () { format: 'duration', expected: '2 years, 11 days', }, + { + datetime: '2024-10-24T14:46:00.000Z', + format: 'duration', + precision: 'year', + expected: '2 years', + }, { datetime: '2024-10-24T14:46:00.000Z', format: 'duration', @@ -2680,6 +2686,12 @@ suite('relative-time', function () { format: 'elapsed', expected: '1y', }, + { + datetime: '2020-10-24T14:46:00.000Z', + format: 'elapsed', + precision: 'year', + expected: '2y', + }, // Dates in the past {