Temporal을 사용한 전역 이벤트 조정

웹 기능: Temporal

기존 Date 객체를 사용하면 여러 시간대에 걸쳐 이벤트를 예약하는 것이 매우 어렵습니다. 특히 일광 절약 시간 (DST) 전환 시에는 시간이 건너뛰거나 반복될 수 있습니다.

Temporal API는 특정 시간대의 날짜와 시간을 나타내는 Temporal.ZonedDateTime를 제공하여 DST 전환을 자동으로 예측 가능하게 처리합니다.

구현 방법

전 세계 이벤트를 조정하고 잠재적인 일광 절약 시간제 충돌을 처리하려면 다음 안내를 따르세요.

  1. 필수: ZonedDateTime 만들기: Temporal.ZonedDateTime.from()를 사용하여 시간대를 인식하는 날짜-시간 객체를 만듭니다.
  2. 필수: 모호성 처리: disambiguation 옵션을 사용하여 시간이 모호하거나 존재하지 않는 경우 (예: 시계 변경 중)의 동작을 제어합니다.
  3. 필수: 시간대 변환: .withTimeZone()을 사용하여 다른 위치의 해당 시간을 확인합니다.

예: 일정 예약 및 충돌 감지

// 1. Define the event time and target time zone
const date = "2025-03-09";
const time = "02:30"; // This time is skipped in New York during Spring Forward
const timeZone = "America/New_York";
const inputStr = `${date}T${time}[${timeZone}]`;

// 2. Detect conflicts using 'reject'
let hasConflict = false;
try {
  // 'reject' throws RangeError if the time is ambiguous or does not exist
  Temporal.ZonedDateTime.from(inputStr, { disambiguation: 'reject' });
} catch (e) {
  if (e instanceof RangeError) {
    hasConflict = true;
    console.log("This time falls in a DST transition gap or overlap.");
  }
}

// 3. Resolve the time safely using 'compatible' (default)
// 'compatible' will resolve to a valid time even if skipped or repeated
const hostTime = Temporal.ZonedDateTime.from(inputStr, { disambiguation: 'compatible' });
console.log(`Resolved time: ${hostTime.toString()}`);

// 4. Convert to another time zone (e.g., Tokyo)
const tokyoTime = hostTime.withTimeZone("Asia/Tokyo");
// Use toLocaleString() for user-facing display instead of manual hour/minute padding
console.log(`Tokyo time: ${tokyoTime.toLocaleString('en-US', { hour: 'numeric', minute: '2-digit' })}`);

전략적 구현 및 권장사항

  • 특정 지리적 위치에 국한된 이벤트 (예: 특정 도시에서 열리는 회의)에는 Temporal.ZonedDateTime를 사용합니다.
  • 일광 절약 시간제 전환 중에 일정 충돌을 감지하고 사용자에게 경고해야 하는 경우 disambiguation: 'reject'를 사용합니다.
  • 권장사항: 충돌이 발생할 때 시스템이 적절한 시간을 자동으로 선택하도록 하려면 disambiguation: 'compatible' (기본값)를 사용합니다.
  • Temporal.PlainDateTime는 시간대 정보를 전달하지 않고 DST 변경사항을 고려할 수 없으므로 전역 이벤트에 사용하지 마세요.
  • 권장사항: .withTimeZone()를 사용하여 원래 객체를 변경하지 않고 다른 위치의 동일한 시간을 계산합니다 (Temporal 객체는 변경할 수 없음).
  • 수동 시간 계산 및 패딩 대신 사용자 대상 시간 표시에 네이티브 .toLocaleString() 형식 지정 (예: { hour: 'numeric', minute: '2-digit' })을 사용합니다.

대체 전략

Temporal의 대체 및 브라우저 지원

아직 네이티브 Temporal API를 지원하지 않는 브라우저의 경우 기능 감지를 사용하고 temporal-polyfill (~15KB min+gz)를 동적으로 로드합니다.

temporal-polyfill를 가져와도 Temporal 객체가 전역 범위에 자동으로 할당되지 않습니다. 코드가 globalThis.Temporal에 의존하는 경우 명시적으로 할당합니다.

// Check if Temporal is supported natively
(async () => {
  if (typeof Temporal === 'undefined') {
    // Load the polyfill conditionally
    const module = await import('https://esm.sh/temporal-polyfill');
    globalThis.Temporal = module.Temporal;
    // Extend Date.prototype if needed
    Date.prototype.toTemporalInstant = module.toTemporalInstant;
  }
  initializeApp();
})();