-
Notifications
You must be signed in to change notification settings - Fork 0
Date 객체
MinJeong Hong edited this page Jan 9, 2026
·
1 revision
이 프로젝트에서 자주 사용되는 Date 관련 패턴들을 정리했습니다.
const now = new Date();
// 또는 (프로젝트에서 사용)
const now = DateTimes.now(); // @woowacourse/mission-utils// ISO 형식 문자열
const date1 = new Date('2024-12-13');
const date2 = new Date('2024-12-13T10:30:00');
// convenience 프로젝트에서 사용
const start_date = new Date('2024-01-01');
const end_date = new Date('2024-12-31');시간대 동작 원리:
JavaScript Date 객체는 자동으로 로컬 시간대를 사용합니다!
// 한국에서 실행하면 자동으로 KST(UTC+9) 기준으로 동작
const now = new Date();
now.getHours(); // 한국 시간 기준 (예: 오후 3시면 15)
now.getDate(); // 한국 날짜 기준하지만 문자열 파싱 시 주의:
// ❌ 문제가 될 수 있음
const date1 = new Date('2024-12-13');
// UTC 기준으로 해석됨 → 한국 시간으로는 12월 13일 오전 9시
// ✅ 해결 방법 1: 시간 포함
const date2 = new Date('2024-12-13T00:00:00+09:00'); // KST 명시
// ✅ 해결 방법 2: 로컬 시간대로 해석 (권장)
const date3 = new Date(2024, 11, 13); // 월은 0-based (11=12월)
// 또는
const date4 = new Date('2024-12-13T00:00:00'); // 로컬 시간대로 해석핵심 정리:
-
new Date()→ 자동으로 한국 시간대(KST) 사용 ✅ -
getMonth(),getDate()등 → 한국 시간 기준 ✅ -
'2024-12-13'형식만 → UTC로 해석될 수 있음⚠️ - 프로젝트에서는 대부분 문제 없음 (날짜만 사용하거나
DateTimes.now()사용)
const date = new Date('2024-12-13');
date.getFullYear(); // 2024 (4자리 연도)
date.getMonth(); // 11 ⚠️ 0-based! (0=1월, 11=12월)
date.getDate(); // 13 (일)
date.getDay(); // 5 (요일: 0=일요일, 6=토요일)
date.getHours(); // 0 (시간, 0-23)
date.getMinutes(); // 0 (분, 0-59)
date.getSeconds(); // 0 (초, 0-59)attendance 프로젝트:
// 요일 가져오기
#getWeekday(day) {
const weekday = ['일', '월', '화', '수', '목', '금', '토'];
const date = new Date(day); // '2024-12-13'
return weekday[date.getDay()]; // '금'
}
// 월/일 추출 (에러 메시지용)
validateWeekday(date) {
const month = date.getMonth() + 1; // ⚠️ 0-based이므로 +1
const day = date.getDate();
// "12월 13일" 형식으로 출력
}핵심 포인트:
-
getMonth()는 0-based (0=1월, 11=12월) → 항상+1필요 -
getDay()는 0=일요일, 6=토요일 -
getDate()는 1-based (1~31)
const date = new Date('2024-12-13');
date.toISOString();
// "2024-12-12T15:00:00.000Z" (UTC 기준)
// attendance 프로젝트에서 사용
const todayDate = DateTimes.now();
const today = todayDate.toISOString().slice(0, 10);
// "2024-12-13" (날짜 부분만 추출)const date = new Date('2024-12-13');
// YYYY-MM-DD 형식
date.toISOString().slice(0, 10); // "2024-12-13"
// 한국어 형식 (직접 포맷팅)
const month = date.getMonth() + 1;
const day = date.getDate();
const formatted = `${month}월 ${day}일`; // "12월 13일"// convenience 프로젝트에서 사용
const now = DateTimes.now();
const startDate = new Date('2024-01-01');
const endDate = new Date('2024-12-31');
endDate.setHours(23, 59, 59, 999); // 하루 끝 시간으로 설정
// 날짜 비교
if (startDate <= now && now <= endDate) {
// 프로모션 활성화
}주의사항:
- Date 객체는 직접 비교 가능 (
<,<=,>,>=) -
==또는===는 같은 객체를 참조하는지 확인 (거의 사용 안 함) - 시간까지 포함해서 비교하려면
setHours()로 시간 설정 필요
const date = new Date('2024-12-13');
// 특정 시간으로 설정
date.setHours(23, 59, 59, 999);
// 23시 59분 59초 999밀리초
// convenience 프로젝트에서 사용
const endDate = new Date(end_date);
endDate.setHours(23, 59, 59, 999);
// 하루의 마지막 시간으로 설정 (프로모션 종료일 포함)요일 확인:
// 문자열 날짜로 요일 가져오기
#getWeekday(day) {
const weekday = ['일', '월', '화', '수', '목', '금', '토'];
const date = new Date(day); // '2024-12-13'
return weekday[date.getDay()]; // '금'
}
// 주말 체크
if (weekday === '일' || weekday === '토') {
// 주말 처리
}현재 날짜 가져오기:
const todayDate = DateTimes.now();
const today = todayDate.toISOString().slice(0, 10); // "2024-12-13"
const day = today.split('-')[2]; // "13"프로모션 기간 확인:
#isPromotionActive(promotionInfo) {
const now = DateTimes.now();
return promotionInfo.some(({ start_date, end_date }) => {
const endDate = new Date(end_date);
endDate.setHours(23, 59, 59, 999); // 하루 끝 시간
return start_date <= now && now <= endDate;
});
}핵심 포인트:
-
end_date는 하루의 마지막 시간(23:59:59)으로 설정해야 함 - 그렇지 않으면 종료일 00:00:00에 이미 종료된 것으로 처리됨
수동으로 요일 계산:
// Date 객체 대신 수동 계산
const weekDayData = ['일', '월', '화', '수', '목', '금', '토'];
const startIndex = weekDayData.indexOf('월'); // 1
// 5월 1일의 요일 계산
const weekDayIndex = (startIndex + 1 - 1) % 7; // 1 (월요일)
const weekday = weekDayData[weekDayIndex]; // '월'중요: JavaScript Date는 자동으로 로컬 시간대를 사용합니다!
// 한국에서 실행하면
const now = new Date();
console.log(now.getHours()); // 한국 시간 (예: 15시 = 오후 3시)
console.log(now.getDate()); // 한국 날짜
// 별도 처리 없이 한국 시간대로 동작함! ✅프로젝트에서 실제 사용:
// attendance 프로젝트
const todayDate = DateTimes.now(); // 한국 시간 기준
const today = todayDate.toISOString().slice(0, 10); // "2024-12-13"
// convenience 프로젝트
const now = DateTimes.now(); // 한국 시간 기준
// 날짜 비교도 한국 시간 기준으로 동작문제가 될 수 있는 경우:
// ❌ 'YYYY-MM-DD' 형식만 있으면 UTC로 해석
const date = new Date('2024-12-13');
// 한국에서 실행해도 UTC 기준 → 12월 13일 00:00:00 UTC
// 한국 시간으로는 12월 13일 09:00:00 KST
console.log(date.getDate()); // 13 (하지만 시간이 9시)해결 방법:
// ✅ 방법 1: 시간대 명시
const date1 = new Date('2024-12-13T00:00:00+09:00'); // KST
// ✅ 방법 2: 생성자 사용 (로컬 시간대)
const date2 = new Date(2024, 11, 13); // 2024년 12월 13일 (로컬 시간)
// ✅ 방법 3: 시간 포함 (로컬 시간대로 해석)
const date3 = new Date('2024-12-13T00:00:00'); // 로컬 시간대프로젝트에서는:
- 대부분 날짜만 사용하거나
DateTimes.now()사용 - 날짜 비교 시 시간 부분은 중요하지 않아서 문제 없음
-
toISOString().slice(0, 10)로 날짜 문자열만 추출하면 시간대 영향 없음
const date = new Date('2024-12-13T15:00:00+09:00'); // 한국 시간 오후 3시
// 로컬 시간대 메서드 (한국 시간 기준)
date.getHours(); // 15 (한국 시간)
date.getDate(); // 13 (한국 날짜)
// UTC 메서드 (UTC 기준)
date.getUTCHours(); // 6 (UTC 시간, 한국 시간 -9시간)
date.getUTCDate(); // 13 (UTC 날짜, 이 경우 같음)프로젝트에서는:
- 대부분 로컬 시간대 메서드 사용 (
getMonth(),getDate()등) - UTC 메서드는 거의 사용 안 함
const date = new Date('2024-12-13');
date.getMonth(); // 11 (12월이지만 11 반환!)
// 올바른 사용
const month = date.getMonth() + 1; // 12// ⚠️ 'YYYY-MM-DD' 형식만 있으면 UTC로 해석
new Date('2024-12-13');
// 한국에서 실행해도 UTC 기준 → 12월 13일 00:00:00 UTC
// 한국 시간으로는 12월 13일 09:00:00 KST
// ✅ 해결 방법들
new Date('2024-12-13T00:00:00+09:00'); // KST 명시
new Date(2024, 11, 13); // 생성자 사용 (로컬 시간대)
new Date('2024-12-13T00:00:00'); // 시간 포함 (로컬 시간대로 해석)실제로는:
- 프로젝트에서 날짜만 사용할 때는 문제 없음
-
toISOString().slice(0, 10)로 날짜 문자열만 추출하면 시간대 영향 없음
// ❌ 문제: 시간이 00:00:00이면 비교가 어려움
const endDate = new Date('2024-12-13');
if (now <= endDate) { // 12월 13일 00:00:00까지만 포함
// ✅ 해결: 하루 끝 시간으로 설정
const endDate = new Date('2024-12-13');
endDate.setHours(23, 59, 59, 999);
if (now <= endDate) { // 12월 13일 23:59:59까지 포함function formatDate(date) {
const weekday = ['일', '월', '화', '수', '목', '금', '토'];
const month = date.getMonth() + 1;
const day = date.getDate();
const weekdayName = weekday[date.getDay()];
return `${month}월 ${day}일 ${weekdayName}요일`;
}
const today = new Date();
console.log(formatDate(today)); // "12월 13일 금요일"function daysBetween(date1, date2) {
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
}
const start = new Date('2024-12-01');
const end = new Date('2024-12-13');
console.log(daysBetween(start, end)); // 12function isWeekend(date) {
const day = date.getDay();
return day === 0 || day === 6; // 일요일(0) 또는 토요일(6)
}
const date = new Date('2024-12-14'); // 토요일
console.log(isWeekend(date)); // true| 메서드 | 설명 | 반환값 범위 | 주의사항 |
|---|---|---|---|
getFullYear() |
연도 | 4자리 숫자 | - |
getMonth() |
월 | 0-11 | 0-based, +1 필요 |
getDate() |
일 | 1-31 | 1-based |
getDay() |
요일 | 0-6 | 0=일요일, 6=토요일 |
getHours() |
시간 | 0-23 | - |
getMinutes() |
분 | 0-59 | - |
getSeconds() |
초 | 0-59 | - |
// 시간 설정
date.setHours(23, 59, 59, 999);
date.setDate(15); // 일 설정
date.setMonth(11); // 월 설정 (0-based)
// 날짜 더하기/빼기
const tomorrow = new Date(date);
tomorrow.setDate(date.getDate() + 1);
// 타임스탬프 (밀리초)
date.getTime(); // 1970-01-01부터의 밀리초
Date.now(); // 현재 타임스탬프-
요일 확인:
new Date(dateString).getDay()→ 배열 인덱스로 요일명 매핑 -
날짜 포맷팅:
getMonth() + 1,getDate()조합 -
날짜 비교: 직접 비교 (
<=,>=) +setHours()로 시간 설정 -
현재 날짜:
DateTimes.now()또는new Date() -
문자열 변환:
toISOString().slice(0, 10)(YYYY-MM-DD)
프로젝트에서 Date를 사용할 때 확인할 사항:
-
getMonth()사용 시+1했는가? - 날짜 비교 시 시간까지 고려했는가? (
setHours()사용) - 요일 확인 시
getDay()가 0=일요일인 것을 고려했는가? - 날짜 문자열 파싱 시 시간대 문제는 없는가? (대부분 문제 없음)
- 종료일 포함 비교 시
23:59:59로 설정했는가? - 한국에서 실행하면 자동으로 KST 사용됨을 이해했는가?
A: 대부분 필요 없습니다!
// ✅ 자동으로 한국 시간대 사용
const now = new Date();
now.getHours(); // 한국 시간
now.getDate(); // 한국 날짜
// ✅ DateTimes.now()도 한국 시간 기준
const today = DateTimes.now();A: 'YYYY-MM-DD' 형식만 파싱할 때
// ⚠️ 이 경우만 주의
const date = new Date('2024-12-13'); // UTC로 해석될 수 있음
// ✅ 해결
const date = new Date(2024, 11, 13); // 로컬 시간대A: 네, 대부분 문제 없습니다!
-
DateTimes.now()사용 → 한국 시간 기준 ✅ - 날짜만 비교 → 시간대 영향 없음 ✅
-
toISOString().slice(0, 10)→ 날짜 문자열만 추출 ✅ -
getMonth(),getDate()→ 한국 시간 기준 ✅