|
| 1 | +import { calendarDurationBetween } from '@/lib/calendar'; |
| 2 | + |
| 3 | +describe('calendarDurationBetween', () => { |
| 4 | + const start = new Date('2018-08-01'); |
| 5 | + |
| 6 | + it('should count full years, months and days since start', () => { |
| 7 | + expect( |
| 8 | + calendarDurationBetween(start, new Date('2026-07-19T12:00:00Z')), |
| 9 | + ).toEqual({ years: 7, months: 11, days: 18 }); |
| 10 | + }); |
| 11 | + |
| 12 | + it('should roll over to a new year on the anniversary date', () => { |
| 13 | + expect( |
| 14 | + calendarDurationBetween(start, new Date('2026-08-01T00:00:00Z')), |
| 15 | + ).toEqual({ years: 8, months: 0, days: 0 }); |
| 16 | + }); |
| 17 | + |
| 18 | + it('should stay at the previous year until the anniversary', () => { |
| 19 | + expect( |
| 20 | + calendarDurationBetween(start, new Date('2026-07-31T23:59:59Z')), |
| 21 | + ).toEqual({ years: 7, months: 11, days: 30 }); |
| 22 | + }); |
| 23 | + |
| 24 | + it('should borrow days from the previous month when end day is smaller', () => { |
| 25 | + expect( |
| 26 | + calendarDurationBetween( |
| 27 | + new Date('2018-08-15'), |
| 28 | + new Date('2026-07-10T00:00:00Z'), |
| 29 | + ), |
| 30 | + ).toEqual({ years: 7, months: 10, days: 25 }); |
| 31 | + }); |
| 32 | + |
| 33 | + it('should compute in UTC regardless of local timezone offset', () => { |
| 34 | + // 23:30 in New York (UTC-4) is already July 20 in UTC |
| 35 | + expect( |
| 36 | + calendarDurationBetween(start, new Date('2026-07-19T23:30:00-04:00')), |
| 37 | + ).toEqual({ years: 7, months: 11, days: 19 }); |
| 38 | + }); |
| 39 | + |
| 40 | + it('should cap month-end anchors to shorter months', () => { |
| 41 | + expect( |
| 42 | + calendarDurationBetween(new Date('2020-01-31'), new Date('2020-03-01')), |
| 43 | + ).toEqual({ years: 0, months: 1, days: 1 }); |
| 44 | + }); |
| 45 | + |
| 46 | + it('should treat a capped february as a full month', () => { |
| 47 | + expect( |
| 48 | + calendarDurationBetween(new Date('2020-01-31'), new Date('2021-02-28')), |
| 49 | + ).toEqual({ years: 1, months: 1, days: 0 }); |
| 50 | + }); |
| 51 | + |
| 52 | + it('should return zeros for the same instant', () => { |
| 53 | + expect(calendarDurationBetween(start, new Date('2018-08-01'))).toEqual({ |
| 54 | + years: 0, |
| 55 | + months: 0, |
| 56 | + days: 0, |
| 57 | + }); |
| 58 | + }); |
| 59 | +}); |
0 commit comments