|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "JavaScript UTC to KST Conversion - 3 Utility Functions for Production" |
| 4 | +date: 2025-01-10 09:00:00 +0900 |
| 5 | +categories: [Development, Tips] |
| 6 | +tags: [JavaScript, UTC, KST, timezone, Date] |
| 7 | +author: "Kevin Park" |
| 8 | +lang: en |
| 9 | +excerpt: "Convert between UTC and Korean Standard Time (KST) in JavaScript without external libraries." |
| 10 | +--- |
| 11 | + |
| 12 | +## Problem |
| 13 | + |
| 14 | +Your backend stores timestamps in UTC, but the frontend needs to display Korean time (KST, UTC+9). `toLocaleString` behavior varies across browsers, so manual conversion is safer. |
| 15 | + |
| 16 | +## Solution |
| 17 | + |
| 18 | +```javascript |
| 19 | +// 1. Korea date string → UTC date |
| 20 | +function toUtcDate(koreaDateStr) { |
| 21 | + const date = new Date(koreaDateStr + 'T00:00:00+09:00'); |
| 22 | + return date.toISOString().split('T')[0]; |
| 23 | +} |
| 24 | + |
| 25 | +// 2. UTC timestamp → Korea date |
| 26 | +function toKoreaDate(utcTimestamp) { |
| 27 | + const date = new Date(utcTimestamp); |
| 28 | + if (isNaN(date.getTime())) return ''; |
| 29 | + const koreaTime = new Date(date.getTime() + 9 * 60 * 60 * 1000); |
| 30 | + return koreaTime.toISOString().split('T')[0]; |
| 31 | +} |
| 32 | + |
| 33 | +// 3. UTC date range for a single Korea day (for API queries) |
| 34 | +function getUtcDateRange(koreaDateStr) { |
| 35 | + const startUtc = toUtcDate(koreaDateStr); |
| 36 | + const nextDay = new Date(koreaDateStr + 'T00:00:00+09:00'); |
| 37 | + nextDay.setDate(nextDay.getDate() + 1); |
| 38 | + const endUtc = toUtcDate(nextDay.toISOString().split('T')[0]); |
| 39 | + return [startUtc, endUtc]; |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +## Key Points |
| 44 | + |
| 45 | +- Midnight in Korea (00:00 KST) is 15:00 UTC the previous day. When querying by date, you need a 2-day UTC range to avoid missing data. |
| 46 | +- Appending `+09:00` offset directly during parsing eliminates the need for timezone libraries. |
| 47 | +- Adding `9 * 60 * 60 * 1000` (32,400,000ms) is simple and works perfectly for Korea since it doesn't observe DST. |
0 commit comments