PageSourceSearch

https://0404.go.kr/js/commons/common_date.js?ver=1790913590225

js 0404.go.kr collected 2026-10-02 04:00:06 UTC 5,782 bytes, 147 lines download raw bytes

1//DateUtils 클래스
2class DateUtils {
3    /**
4     * 날짜를 지정된 포맷으로 변환하는 함수
5     * @param {Date} date 변환할 날짜 객체 (기본값: 현재 날짜)
6     * @param {string} format 원하는 출력 형식 (예: 'yyyy-mm-dd', 'dd/mm/yyyy')
7     * @returns {string} 포맷팅된 날짜 문자열
8     */
9    static formatDate(date = new Date(), format = 'yyyy-mm-dd') {
10        const yyyy = date.getFullYear();
11        const mm = String(date.getMonth() + 1).padStart(2, '0');
12        const dd = String(date.getDate()).padStart(2, '0');
13        return format.replace('yyyy', yyyy).replace('mm', mm).replace('dd', dd);
14    }
15
16    /**
17     * 날짜를 추가하거나 빼는 함수
18     * @param {Date} date 기준 날짜
19     * @param {number} value 더할 값 (음수면 빼기)
20     * @param {'days' | 'months' | 'years'} unit 단위 (days, months, years)
21     * @returns {Date} 계산된 새로운 날짜 객체
22     */
23    static addDate(date, value, unit) {
24        if (typeof date === 'string') date = new Date(date); // 문자열을 Date 객체로 변환
25
26        if (!(date instanceof Date) || isNaN(date)) throw new Error("유효한 날짜를 입력하세요.");
27
28        // value가 문자열이면 숫자로 변환 시도
29        value = Number(value);
30        if (isNaN(value)) throw new Error("value는 숫자여야 합니다.");
31
32        const newDate = new Date(date);
33        if (unit === 'days') newDate.setDate(newDate.getDate() + value);
34        if (unit === 'months') newDate.setMonth(newDate.getMonth() + value);
35        if (unit === 'years') newDate.setFullYear(newDate.getFullYear() + value);
36
37        return newDate;
38    }
39
40
41    /**
42     * 두 날짜 간 차이 계산 (일 단위)
43     * @param {Date} date1 첫 번째 날짜
44     * @param {Date} date2 두 번째 날짜
45     * @returns {number} 날짜 차이 (일 단위)
46     */
47    static diffDays(date1, date2) {
48        return Math.ceil((date2 - date1) / (1000 * 60 * 60 * 24));
49    }
50
51    /**
52     * 주어진 날짜가 주말인지 확인
53     * @param {Date} date 검사할 날짜
54     * @returns {boolean} 주말 여부 (true: 주말, false: 평일)
55     */
56    static isWeekend(date) {
57        return date.getDay() === 0 || date.getDay() === 6;
58    }
59
60    /**
61     * 주어진 연도가 윤년인지 확인
62     * @param {number} year 검사할 연도
63     * @returns {boolean} 윤년 여부 (true: 윤년, false: 평년)
64     */
65    static isLeapYear(year) {
66        return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
67    }
68
69    /**
70     * 유효한 날짜인지 확인
71     * @param {Date} date 검사할 날짜
72     * @returns {boolean} 유효한 날짜 여부
73     */
74    static isValidDate(date) {
75        return date instanceof Date && !isNaN(date);
76    }
77
78    /**
79     * 해당 월의 마지막 날짜 반환
80     * @param {number} year 연도
81     * @param {number} month 월 (1~12)
82     * @returns {number} 해당 월의 마지막 날짜
83     */
84    static getLastDayOfMonth(year, month) {
85        return new Date(year, month, 0).getDate();
86    }
87
88    /**
89     * 주어진 날짜가 공휴일인지 확인
90     * @param {Date} date 검사할 날짜
91     * @param {string[]} holidays 공휴일 목록 (기본값: 새해 첫날 & 크리스마스)
92     * @returns {boolean} 공휴일 여부
93     */
94    static isHoliday(date, holidays = ['2025-01-01', '2025-12-25']) {
95        return holidays.includes(this.formatDate(date, 'yyyy-mm-dd'));
96    }
97
98    /**
99     * 두 날짜 간 시간 차이 계산 (시간, 분, 초)
100     * @param {Date} date1 첫 번째 날짜
101     * @param {Date} date2 두 번째 날짜
102     * @returns {{hours: number, minutes: number, seconds: number}} 차이 객체
103     */
104    static diffTime(date1, date2) {
105        const diffMs = Math.abs(date2 - date1);
106        return {
107            hours: Math.floor(diffMs / (1000 * 60 * 60)),
108            minutes: Math.floor((diffMs / (1000 * 60)) % 60),
109            seconds: Math.floor((diffMs / 1000) % 60)
110        };
111    }
112
113    /**
114     * 해당 날짜의 ISO 8601 주 번호 반환
115     * @param {Date} date 검사할 날짜
116     * @returns {number} 해당 날짜의 주 번호
117     */
118    static getWeekNumber(date) {
119        const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
120        const pastDaysOfYear = (date - firstDayOfYear) / (1000 * 60 * 60 * 24);
121        return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
122    }
123
124    /**
125     * 특정 요일의 다음 날짜 찾기
126     * @param {Date} date 기준 날짜
127     * @param {number} dayOfWeek 원하는 요일 (0: 일요일, 6: 토요일)
128     * @returns {Date} 해당 요일의 다음 날짜
129     */
130    static getNextDayOfWeek(date, dayOfWeek) {
131        const resultDate = new Date(date);
132        resultDate.setDate(date.getDate() + ((dayOfWeek + 7 - date.getDay()) % 7));
133        return resultDate;
134    }
135}
136
137// 사용 예시
138/*const today = new Date();
139console.log('오늘 날짜:', DateUtils.formatDate(today, 'yyyy-mm-dd')); // 2025-03-13
140console.log('일주일 전:', DateUtils.formatDate(DateUtils.addDate(today, -7, 'days'), 'yyyy-mm-dd')); // 7일 전
141console.log('한 달 후:', DateUtils.formatDate(DateUtils.addDate(today, 1, 'months'), 'yyyy-mm-dd')); // 1달 후
142console.log('올해는 윤년인가?', DateUtils.isLeapYear(today.getFullYear()));
142 // 윤년 여부
143console.log('주말인가?', DateUtils.isWeekend(today)); // 오늘이 주말인지 확인*/
144
145// 두 날짜 차이 계산
146/*const anotherDate = new Date('2025-04-01');
147console.log('날짜 차이:', DateUtils.diffDays(today, anotherDate), '일'); // 날짜 차이 계산*/

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.