Date 객체: 오래됐지만 여전히 핵심
JavaScript의 Date 객체는 1995년부터 언어의 일부였습니다. 내부적으로 Unix epoch(UTC) 이후의 밀리초로 저장하지만, 대부분의 메서드는 현지 시간을 반환합니다:
const now = new Date();
const fromISO = new Date("2024-03-01T14:00:00Z");
// UTC 값 (어디서나 일관성)
now.getUTCHours() // 항상 UTC
now.toISOString() // "2024-03-01T14:00:00.000Z"
// 현지 값 (브라우저 시간대에 따라 다름)
now.getHours()
now.toLocaleDateString("ko-KR") // "2024. 3. 1."
Intl.DateTimeFormat: 로케일 인식 포맷팅
const d = new Date("2024-03-01T14:00:00Z");
new Intl.DateTimeFormat("ko-KR", {
timeZone: "Asia/Seoul",
year: "numeric", month: "long", day: "numeric",
hour: "2-digit", minute: "2-digit",
hour12: false,
}).format(d);
// "2024년 3월 1일 23:00"
// 상대 시간
new Intl.RelativeTimeFormat("ko", { numeric: "auto" })
.format(-1, "day"); // "어제"
.format(3, "hour"); // "3시간 후"
Performance.now(): 고해상도 타이밍
코드 성능 측정에는 Date.now() 대신 performance.now()를 사용하세요. 페이지 로드 이후 밀리초를 밀리초 이하 정밀도로 반환하며 시스템 시계 조정의 영향을 받지 않습니다.
브라우저 시간대 감지
// 사용자의 IANA 시간대 이름 가져오기
Intl.DateTimeFormat().resolvedOptions().timeZone
// "Asia/Seoul", "America/New_York" 등
// UTC 오프셋 (분 단위)
new Date().getTimezoneOffset() // KST의 경우 -540
Temporal API (곧 출시)
Temporal API(TC39 Stage 3)는 Date의 모든 문제를 해결합니다. 현재 폴리필을 사용할 수 있습니다:
import { Temporal } from "@js-temporal/polyfill";
const now = Temporal.Now.zonedDateTimeISO("Asia/Seoul");
console.log(now.toString());
// 2024-03-01T23:00:00+09:00[Asia/Seoul]