|
1 | | -import { isWeekend, DayOfWeek } from '../../src/common/date'; |
| 1 | +import { formatInTimeZone } from 'date-fns-tz'; |
| 2 | +import { |
| 3 | + isWeekend, |
| 4 | + DayOfWeek, |
| 5 | + secondsUntilNextHourInTimezone, |
| 6 | +} from '../../src/common/date'; |
| 7 | +import { ONE_DAY_IN_SECONDS } from '../../src/common/constants'; |
2 | 8 |
|
3 | 9 | describe('date', () => { |
| 10 | + describe('secondsUntilNextHourInTimezone', () => { |
| 11 | + const expiryAt = (now: Date, ttl: number): Date => |
| 12 | + new Date(now.getTime() + ttl * 1000); |
| 13 | + |
| 14 | + it('should expire at the next 9am in the given timezone', () => { |
| 15 | + const now = new Date('2026-06-19T06:00:00Z'); |
| 16 | + |
| 17 | + ['Etc/UTC', 'America/New_York', 'Asia/Tokyo'].forEach((timezone) => { |
| 18 | + const ttl = secondsUntilNextHourInTimezone({ hour: 9, timezone, now }); |
| 19 | + |
| 20 | + expect(ttl).toBeGreaterThan(0); |
| 21 | + expect(ttl).toBeLessThanOrEqual(ONE_DAY_IN_SECONDS); |
| 22 | + expect(formatInTimeZone(expiryAt(now, ttl), timezone, 'HH:mm')).toBe( |
| 23 | + '09:00', |
| 24 | + ); |
| 25 | + expect(expiryAt(now, ttl).getTime()).toBeGreaterThan(now.getTime()); |
| 26 | + }); |
| 27 | + }); |
| 28 | + |
| 29 | + it('should roll to the next day once 9am has passed in the timezone', () => { |
| 30 | + // 23:00 UTC is already past 9am UTC today, so it targets tomorrow. |
| 31 | + const now = new Date('2026-06-19T23:00:00Z'); |
| 32 | + const ttl = secondsUntilNextHourInTimezone({ |
| 33 | + hour: 9, |
| 34 | + timezone: 'Etc/UTC', |
| 35 | + now, |
| 36 | + }); |
| 37 | + |
| 38 | + expect( |
| 39 | + formatInTimeZone(expiryAt(now, ttl), 'Etc/UTC', 'yyyy-MM-dd HH:mm'), |
| 40 | + ).toBe('2026-06-20 09:00'); |
| 41 | + }); |
| 42 | + |
| 43 | + it('should shift with the timezone for the same instant', () => { |
| 44 | + const now = new Date('2026-06-19T06:00:00Z'); |
| 45 | + const utc = secondsUntilNextHourInTimezone({ |
| 46 | + hour: 9, |
| 47 | + timezone: 'Etc/UTC', |
| 48 | + now, |
| 49 | + }); |
| 50 | + const tokyo = secondsUntilNextHourInTimezone({ |
| 51 | + hour: 9, |
| 52 | + timezone: 'Asia/Tokyo', |
| 53 | + now, |
| 54 | + }); |
| 55 | + |
| 56 | + expect(utc).not.toEqual(tokyo); |
| 57 | + }); |
| 58 | + }); |
| 59 | + |
4 | 60 | describe('isWeekend', () => { |
5 | 61 | it('should return true for Saturday and Sunday when the week starts on Monday', () => { |
6 | 62 | expect(isWeekend(new Date('2024-08-10'), DayOfWeek.Monday)).toBe(true); // Saturday |
|
0 commit comments