active-hours.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import type { ActiveHoursConfig } from './types.js';
  2. export function getCurrentTime(timezone?: string): { hours: number; minutes: number } {
  3. const now = new Date();
  4. if (!timezone) {
  5. return { hours: now.getHours(), minutes: now.getMinutes() };
  6. }
  7. const formatter = new Intl.DateTimeFormat('en-US', {
  8. timeZone: timezone,
  9. hour: 'numeric',
  10. minute: 'numeric',
  11. hour12: false,
  12. });
  13. const parts = formatter.formatToParts(now);
  14. const hours = Number(parts.find((p) => p.type === 'hour')?.value ?? 0);
  15. const minutes = Number(parts.find((p) => p.type === 'minute')?.value ?? 0);
  16. return { hours, minutes };
  17. }
  18. export function parseTime(timeStr: string): { hours: number; minutes: number } {
  19. const [h, m] = timeStr.split(':');
  20. return { hours: Number(h), minutes: Number(m) };
  21. }
  22. export function timeToMinutes(t: { hours: number; minutes: number }): number {
  23. return t.hours * 60 + t.minutes;
  24. }
  25. /** Check if current time is within the active hours window. Returns true if no activeHours configured. */
  26. export function isWithinActiveHours(
  27. activeHours: ActiveHoursConfig | undefined,
  28. timezone?: string,
  29. ): boolean {
  30. if (!activeHours) return true;
  31. const current = timeToMinutes(getCurrentTime(timezone));
  32. const start = timeToMinutes(parseTime(activeHours.start));
  33. const end = timeToMinutes(parseTime(activeHours.end));
  34. if (start <= end) {
  35. return current >= start && current < end;
  36. }
  37. // Midnight-spanning: e.g. 22:00-06:00
  38. return current >= start || current < end;
  39. }