Javascript - Temporal API

post-thumbnail

Temporal API?

Temporal API는 기존의 Date 객체를 대체하기 위해 제안된 최신 날짜 및 시간 처리 API입니다. 자바스크립트의 Date는 1995년부터 유지되어 온 구식 API로 (결함이 많았던 JAVA의 java.util.Date에서 가져왔다), 시간대 처리 불가, 변경 가능한 객체, 불확실한 파싱 등 많은 문제점을 가지고 있습니다. Temporal은 이러한 문제를 근본적으로 해결하고자 설계되었습니다.

기존 Date 객체의 문제점

  • UTC와 로컬시간만 지원,시간대를 명시적으로 지원하지 않음.
  • 객체가 변경 가능(mutable)하여 예측하지 못한 버그가 발생할 수 있다.
  • 파싱 동작이 브라우저마다 달라 신뢰성이 떨어진다.
  • 날짜 연산이 불편하고 실수가 잦다.
  • 그레고리력 외의 달력(음력 등)을 사용할 수 없다.
  • 위 문제점으로 인해 외부 라이브러리(moment.js, date-fns 등)에 의존해야 한다.

주요 특징

  • 시간대 지원: Temporal.ZonedDateTime을 통해 명시적으로 시간대를 지정할 수 있어, 서머타임(DST) 등의 복잡한 시간 계산을 간편하게 처리 가능
  • 정확성 및 불변성: 모든 Temporal 객체는 불변(immutable)이며, 예측 가능한 동작을 보장
  • 캘린더 시스템 지원: 그레고리력 외에도 히브리력, 이슬람력, 중국력 등 다양한 달력을 지원
  • 풍부한 메서드: 200개 이상의 유틸리티 메서드를 통해 다양한 날짜 및 시간 연산을 지원
  • 고정밀도 시간 처리: 나노초 단위까지의 정밀한 시간 측정이 가능
  • 정확한 파싱 및 포맷팅: 엄격한 ISO 8601 형식을 사용하여 일관된 날짜 파싱과 포맷팅이 가능

데이터 타입 요약

  • Temporal.Now : 현재 시점을 다양한 포맷으로 제공
  • Temporal.Instant : UTC 기준 시점 (밀리초/나노초 단위)
  • Temporal.PlainDate: 시간 없는 날짜 표현
  • Temporal.PlainTime: 날짜 없는 시간 표현
  • Temporal.Duration: 두 날짜/시간 간의 간격
  • Temporal.ZonedDateTime: 시간대 포함 날짜 및 시간
  • Temporal.TimeZone: 명시적인 시간대 객체
  • Temporal.Calendar: 비그레고리력 등 다른 달력 시스템 지원

사용 예시

1. 현재 날짜 및 시간 가져오기

// 시스템 시간대 기준 현재 날짜 및 시간
const now = Temporal.Now.plainDateTimeISO();
console.log(now.toString()); // 예: 2025-05-06T23:54:55.000

2. 특정 시간대의 현재 시간 가져오기

// "America/New_York" 시간대의 현재 날짜 및 시간
const nyTime = Temporal.Now.plainDateTimeISO("America/New_York");
console.log(nyTime.toString()); 
// 예: 2025-05-06T10:54:55.000

3. 두 날짜 간의 기간 계산

const start = Temporal.PlainDate.from('2025-01-01');
const end = Temporal.PlainDate.from('2025-05-06');
const duration = end.since(start);
console.log(duration.toString()); // 예: P4M5D

4. 시간대 변환

const meetingInNY = Temporal.ZonedDateTime.from({
  year: 2025,
  month: 5,
  day: 6,
  hour: 10,
  timeZone: 'America/New_York'
});
const meetingInSeoul = meetingInNY.withTimeZone('Asia/Seoul');
console.log(meetingInSeoul.toString()); // 예: 2025-05-06T23:00:00+09:00[Asia/Seoul]

5. 캘린더 사용

const chineseNewYear = Temporal.PlainMonthDay.from({
  monthCode: "M01",
  day: 1,
  calendar: "chinese",
});
const currentYear = Temporal.Now.plainDateISO().withCalendar("chinese").year;
let nextCNY = chineseNewYear.toPlainDate({ year: currentYear });

if (Temporal.PlainDate.compare(nextCNY, Temporal.Now.plainDateISO()) <= 0) {
  nextCNY = nextCNY.add({ years: 1 });
}
console.log(
  `다음 중국 설날은 ${nextCNY.withCalendar("iso8601").toLocaleString()}입니다.`
);
// 예: 2025년 1월 29일

6. 시간 정렬

const durations = [
  Temporal.Duration.from({ hours: 1 }),
  Temporal.Duration.from({ hours: 2 }),
  Temporal.Duration.from({ hours: 1, minutes: 30 }),
  Temporal.Duration.from({ hours: 1, minutes: 45 }),
];
durations.sort(Temporal.Duration.compare);
console.log(durations.map((d) => d.toString()));
// 결과: [ 'PT1H', 'PT1H30M', 'PT1H45M', 'PT2H' ]

폴리필 사용 방법

브라우저에서 Temporal API를 지원하지 않는 경우, 공식 폴리필인 @js-temporal/polyfill을 사용하면 된다.

npm install @js-temporal/polyfil
import { Temporal } from '@js-temporal/polyfill';

reference

https://tc39.es/proposal-temporal/docs/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal
https://developer.mozilla.org/en-US/blog/javascript-temporal-is-coming/

0개의 댓글