
자바스크립트의 표준 빌트인 객체인 Date 객체는 날짜와 시간을 처리할 수 있는 유용한 객체이다. Date 객체를 사용하면 특정 날짜와 시간을 생성하거나, 현재 시간을 불러오는 등의 다양한 작업이 가능하므로 제대로 정리하고 넘어가보자.
new 연산자와 함께 호출하면 현재 날짜와 시간을 가지는 Date 객체를 반환한다.new 연산자 없이 호출하면 Date 객체가 아닌 날짜와 시간 정보를 나타내는 문자열을 반환한다.const now = new Date();
console.log(now); // Sun Nov 03 2024 21:05:27 GMT+0900 (한국 표준시)
Date(); // 'Sun Nov 03 2024 21:06:37 GMT+0900 (한국 표준시)'
new Date(year, monthIndex, day, hour, minute, second, millisecond) 형식을 사용한다.monthIndex는 0부터 시작하므로 0이 1월, 11이 12월을 나타낸다.const specificDate = new Date(2023, 0, 1, 10, 30, 0, 0); // 2023년 1월 1일 오전 10시 30분
YYYY-MM-DD가 가장 일반적이며, YYYY/MM/DD도 사용할 수 있다.const dateFromString = new Date("2023-01-01");
const dateFromTimestamp = new Date(1672531200000);
const timestamp = Date.now();
console.log(timestamp); // 예: 1698875098123
const timestamp = Date.parse("2024-11-03T14:30:00");
console.log(timestamp); // 예: 1730653800000
const timestampUTC = Date.UTC(2024, 10, 3, 14, 30, 0);
console.log(timestampUTC); // 예: 1730653800000
const year = now.getFullYear(); // 2024
const month = now.getMonth(); // 0 (1월)
const day = now.getDate(); // 1일
const dayOfWeek = now.getDay(); // 예: 2 (화요일)
const hours = now.getHours(); // 예: 14 (오후 2시)
const minutes = now.getMinutes(); // 예: 30
const seconds = now.getSeconds(); // 예: 45
const milliseconds = now.getMilliseconds(); // 예: 123
const timestamp = now.getTime();
now.setFullYear(2025, 11, 25); // 2025년 12월 25일로 설정
now.setMonth(6); // 7월로 설정
now.setDate(15); // 15일로 설정
now.setHours(18, 30, 0, 0); // 오후 6시 30분으로 설정
date.setMinutes(45, 30, 500); // Sun Nov 03 2024 21:45:30 GMT+0900 (한국 표준시)
date.setSeconds(30, 500); // Sun Nov 03 2024 21:26:30 GMT+0900 (한국 표준시)
date.setMilliseconds(500); Sun Nov 03 2024 21:27:20 GMT+0900 (한국 표준시)
date.setTime(1730653800000); // Mon Nov 04 2024 02:10:00 GMT+0900 (한국 표준시)
const timezoneOffset = new Date().getTimezoneOffset();
console.log(timezoneOffset); // 예: -540 (한국 표준시는 UTC+9이므로 -540분)
const date = new Date();
console.log(date.toDateString()); // 예: "Sun Nov 03 2024"
const date = new Date();
console.log(date.toTimeString()); // 예: "14:30:00 GMT+0900 (Korean Standard Time)"
Z(UTC를 의미)를 끝에 붙여준다.const date = new Date();
console.log(date.toISOString()); // 예: "2024-11-03T05:30:00.000Z"
const date = new Date();
console.log(date.toLocaleString("ko-KR")); // 예: "2024. 11. 3. 오후 2:30:00"
const date = new Date();
const formattedDate = date.toLocaleDateString("ko-KR", {
year: "numeric",
month: "long",
day: "numeric",
weekday: "long"
});
console.log(formattedDate); // 예: "2024년 11월 3일 일요일"
const formattedTime = date.toLocaleTimeString("ko-KR", {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
});
console.log(formattedTime); // 예: "14:30:00"