본문으로 건너뛰기
김신건의 로그

[Javascript] Date

· 수정 · 📖 약 1분 · 293자/단어 #javascript #date #datetime
JS Date, JavaScript Date, Date 객체

정의

JS 의 Date 객체. 시간을 ms 단위로 (1970-01-01T00:00:00Z 기준) 저장. 매우 오래된 API 라 함정이 많다.

생성

new Date();                              // 현재 시각
new Date('2024-01-15');                  // ISO string
new Date('2024-01-15T09:00:00Z');        // UTC
new Date('2024-01-15T09:00:00+09:00');   // timezone
new Date(2024, 0, 15);                   // 년, 월(0-base!), 일
new Date(1705248000000);                 // unix ms
Date.now();                              // 현재 ms (Date 객체 X)

CAUTION

월이 0-base (0=1월). 가장 흔한 함정.

가져오기

const d = new Date('2024-01-15T09:00:00');
d.getFullYear();        // 2024
d.getMonth();           // 0 (1월!)
d.getDate();            // 15 (일)
d.getDay();             // 1 (요일, 0=일요일)
d.getHours();           // 9
d.getMinutes();
d.getSeconds();
d.getMilliseconds();
d.getTime();            // unix ms
d.getTimezoneOffset();  // 분 (UTC 기준)

// UTC 버전
d.getUTCFullYear();
d.getUTCHours();

출력

d.toISOString();         // '2024-01-15T00:00:00.000Z'
d.toJSON();              // 같음
d.toUTCString();         // 'Mon, 15 Jan 2024 00:00:00 GMT'
d.toString();            // 시스템 timezone 문자열
d.toLocaleString();      // '2024. 1. 15. 오전 9:00:00' (ko-KR)
d.toLocaleDateString();
d.toLocaleTimeString();

Intl.DateTimeFormat (권장)

const fmt = new Intl.DateTimeFormat('ko-KR', {
    year: 'numeric', month: 'long', day: 'numeric',
    weekday: 'short',
});
fmt.format(d);    // '2024년 1월 15일 (월)'

new Intl.DateTimeFormat('en-US', {
    timeZone: 'America/New_York',
    dateStyle: 'full', timeStyle: 'short',
}).format(d);

Intl 이 모던 권장. timezone, locale 지원.

산술

const d = new Date();
d.setDate(d.getDate() + 7);          // 7 일 후

// 또는 ms 단위
const future = new Date(d.getTime() + 7 * 24 * 60 * 60 * 1000);

// 차이
const diff = (d2 - d1) / 1000 / 60 / 60 / 24;   // 일 단위

비교

d1 < d2                  // 비교 가능 (ms 변환)
d1.getTime() === d2.getTime()    // 같은 시각 검사
d1 === d2                // 객체 참조, 다르면 false

객체 동등성은 === 로 비교 안 됨. .getTime() 필요.

일반적인 함정

1. 월의 0-base

new Date(2024, 1, 15)       // 2024년 2월 15일! (1월 아님)
new Date('2024-02-15')      // 2024년 2월 15일 (ISO 문자열은 1-base)

2. timezone 추론

new Date('2024-01-15')           // UTC 자정 (Z 가정)
new Date('2024-01-15 09:00')     // local timezone ⚠️
new Date('2024-01-15T09:00')     // local
new Date('2024-01-15T09:00Z')    // UTC

명시적 ISO 8601 (T + Z 또는 +09:00) 권장.

3. Date 의 가변성

const d = new Date();
d.setDate(d.getDate() + 1);    // d 가 변경됨

// 불변 패턴
const tomorrow = new Date(d);
tomorrow.setDate(tomorrow.getDate() + 1);

4. Invalid Date

new Date('invalid')      // Invalid Date
isNaN(d.getTime())       // true

명시적 검사 필요.

5. 윤년 / 28-31일 차이

new Date(2024, 1, 30)      // 2024-02-30 → 자동으로 2024-03-01

월에 없는 날짜는 다음 월로 넘어감 (의도 아닐 가능성).

대안 라이브러리

Date 의 함정 때문에 외부 라이브러리가 흔히 쓰인다.

라이브러리특징
date-fns함수형, tree-shakable
dayjsmoment.js 호환, 가벼움 (2KB)
luxontimezone / Intl 강화
Temporal (ES proposal)차세대 표준, 곧 도입
import { addDays, format } from 'date-fns';
import dayjs from 'dayjs';

addDays(new Date(), 7);
dayjs().add(7, 'day').format('YYYY-MM-DD');

Temporal (proposal)

ECMAScript Temporal 제안. 더 명확한 API.

// 미래에 표준
Temporal.Now.plainDateISO();              // '2024-01-15'
Temporal.PlainDate.from('2024-01-15');
Temporal.ZonedDateTime.from({ ... });

현재는 polyfill (@js-temporal/polyfill) 로 사용 가능.

자주 쓰는 idiom

// 오늘 자정
const today = new Date(); today.setHours(0, 0, 0, 0);

// 이 달 1일
const firstDay = new Date(d.getFullYear(), d.getMonth(), 1);

// 이 달 마지막 날
const lastDay = new Date(d.getFullYear(), d.getMonth() + 1, 0);

// unix timestamp
Math.floor(Date.now() / 1000);

관련 위키

💬 댓글

사이트 검색 / 명령어

검색

스크롤 = 확대/축소 · 드래그 = 이동 · 0 = 원래 크기 · ESC = 닫기