|
1 | 1 | const KST_DIFF = 9 * 60 * 60 * 1000;
|
2 | 2 |
|
| 3 | +/** |
| 4 | + * KST로 변환된 날짜 정보를 담는 인터페이스 |
| 5 | + */ |
| 6 | +export interface KSTDateFormat { |
| 7 | + /** "YYYY-MM-DD" 형식의 날짜 문자열 */ |
| 8 | + short: string; |
| 9 | + |
| 10 | + /** ISO 8601 형식 + KST 오프셋 포함 문자열 */ |
| 11 | + iso: string; |
| 12 | + |
| 13 | + /** KST로 보정된 Date 객체 */ |
| 14 | + full: Date; |
| 15 | +} |
| 16 | + |
3 | 17 | /**
|
4 | 18 | * 주어진 날짜 문자열을 KST(한국 표준시) 기준으로 변환함.
|
5 | 19 | *
|
6 | 20 | * @param {string} [date] - 변환할 날짜 문자열 (예: "2025-05-15T08:00:00Z")
|
7 |
| - * @returns {{ |
8 |
| - * short: string; // "YYYY-MM-DD" 형식의 날짜 문자열 |
9 |
| - * iso: string; // ISO 8601 형식 + KST 오프셋 포함 문자열 |
10 |
| - * full: Date; // KST로 보정된 Date 객체 |
11 |
| - * } | undefined} 날짜가 없으면 undefined 반환 |
| 21 | + * @returns {KSTDateFormat | undefined} 날짜가 없으면 undefined 반환 |
12 | 22 | */
|
13 | 23 |
|
14 |
| -export const convertDateToKST = (date?: string) => { |
| 24 | +export const convertDateToKST = (date?: string): KSTDateFormat | undefined => { |
15 | 25 | if (!date) return;
|
16 |
| - const converted = new Date(new Date(date).getTime() + KST_DIFF); |
17 | 26 |
|
18 |
| - const year = converted.getFullYear(); |
19 |
| - const month = (converted.getMonth() + 1).toString().padStart(2, '0'); |
20 |
| - const day = converted.getDate().toString().padStart(2, '0'); |
21 |
| - const hours = converted.getHours().toString().padStart(2, '0'); |
22 |
| - const minutes = converted.getMinutes().toString().padStart(2, '0'); |
23 |
| - const seconds = converted.getSeconds().toString().padStart(2, '0'); |
| 27 | + // UTC 날짜 파싱 |
| 28 | + const utcDate = new Date(date); |
| 29 | + |
| 30 | + // UTC+9 (KST) 시간으로 변환 |
| 31 | + const kstTimestamp = utcDate.getTime() + KST_DIFF; |
| 32 | + const kstDate = new Date(kstTimestamp); |
| 33 | + |
| 34 | + // UTC 메서드를 사용하여 KST 시간을 추출 |
| 35 | + // (UTC 메서드에 KST 시간을 넣으면 원하는 결과를 얻을 수 있음) |
| 36 | + const year = kstDate.getUTCFullYear(); |
| 37 | + const month = (kstDate.getUTCMonth() + 1).toString().padStart(2, '0'); |
| 38 | + const day = kstDate.getUTCDate().toString().padStart(2, '0'); |
| 39 | + const hours = kstDate.getUTCHours().toString().padStart(2, '0'); |
| 40 | + const minutes = kstDate.getUTCMinutes().toString().padStart(2, '0'); |
| 41 | + const seconds = kstDate.getUTCSeconds().toString().padStart(2, '0'); |
24 | 42 |
|
25 | 43 | return {
|
26 |
| - short: `${converted.getFullYear()}-${(converted.getMonth() + 1).toString().padStart(2, '0')}-${converted.getDate()}`, |
| 44 | + short: `${year}-${month}-${day}`, |
27 | 45 | iso: `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+09:00`,
|
28 |
| - full: converted, |
| 46 | + full: kstDate, |
29 | 47 | };
|
30 | 48 | };
|
0 commit comments