Skip to content

Commit

Permalink
Merge pull request #296 from wxiaoguang/fix-dur
Browse files Browse the repository at this point in the history
Fix duration calculation
  • Loading branch information
francinelucca authored Dec 5, 2024
2 parents e914da2 + da833cf commit bc1b8b7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export function roundToSingleUnit(duration: Duration, {relativeTo = Date.now()}:
days = daysDiff
}
months = years = 0
} else if (monthsDiff < 11) {
} else if (monthsDiff <= 11) {
months = monthsDiff
years = 0
} else {
Expand Down
6 changes: 3 additions & 3 deletions test/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,8 @@ suite('duration', function () {
},
],
['P9M20DT25H', 'P10M', {relativeTo: new Date('2023-01-12T00:00:00Z')}],
['P11M', 'P1Y', {relativeTo: new Date('2022-11-01T00:00:00Z')}],
['-P11M', '-P1Y', {relativeTo: new Date('2022-11-01T00:00:00Z')}],
['P11M', 'P11M', {relativeTo: new Date('2022-11-01T00:00:00Z')}],
['-P11M', '-P11M', {relativeTo: new Date('2022-11-01T00:00:00Z')}],
['-P11M15D', '-P1Y', {relativeTo: new Date('2024-01-06T00:00:00')}],
['P1Y4D', 'P1Y', {relativeTo: new Date('2022-11-01T00:00:00Z')}],
['P1Y5M13D', 'P1Y', {relativeTo: new Date('2023-01-01T00:00:00Z')}],
Expand Down Expand Up @@ -429,7 +429,7 @@ suite('duration', function () {
relativeTo: new Date('2022-12-01T00:00:00Z'),
},
],
['P11M', [1, 'year']],
['P11M', [11, 'month']],
['P1Y4D', [1, 'year']],
[
'P1Y5M13D',
Expand Down
13 changes: 11 additions & 2 deletions test/relative-time.js
Original file line number Diff line number Diff line change
Expand Up @@ -600,13 +600,15 @@ suite('relative-time', function () {
})

test('micro formats years', async () => {
const now = new Date(Date.now() + 10 * 365 * 24 * 60 * 60 * 1000).toISOString()
// FIXME: there is still a bug, if the duration is long enough (say, 10 or 100 years)
// then the `month = Math.floor(day / 30)` in elapsedTime causes errors, then "10 years" would output "11y"
const now = new Date(Date.now() + 2 * 365 * 24 * 60 * 60 * 1000).toISOString()
const time = document.createElement('relative-time')
time.setAttribute('tense', 'future')
time.setAttribute('datetime', now)
time.setAttribute('format', 'micro')
await Promise.resolve()
assert.equal(time.shadowRoot.textContent, '10y')
assert.equal(time.shadowRoot.textContent, '2y')
})

test('micro formats past times', async () => {
Expand Down Expand Up @@ -2498,6 +2500,13 @@ suite('relative-time', function () {
format: 'auto',
expected: '4 years ago',
},
{
reference: '2024-12-04T00:00:00.000Z',
datetime: '2024-01-16T00:00:00.000Z',
tense: 'past',
format: 'auto',
expected: '11 months ago',
},
])

for (const {
Expand Down

0 comments on commit bc1b8b7

Please sign in to comment.