Guide

UTC 타임스탬프 작업 - 전체 가이드

소개

UTC(협정 세계시)는 컴퓨팅 및 네트워크에 사용되는 표준 시간 기준입니다. 여러 시간대에 걸쳐 작동하고 정확한 시간 계산이 필요한 애플리케이션을 구축하려면 UTC 타임스탬프 작업 방법을 이해하는 것이 필수적입니다.

UTC 이해하기

UTC 시간이란 무엇입니까?

UTC는 다음과 같은 시간 표준입니다.

  • 시간대 오프셋이 없습니다(일광 절약 시간 없음).
  • 24시간 형식(00:00:00~23:59:59.999)을 사용합니다.
  • ISO 8601에서는 "Z"로 표현됩니다. (예: 2025-01-07T12:00:00.000Z)
  • 다른 모든 시간대의 기준으로 사용됩니다.

UTC와 현지 시간

중요 개념: 현지 시간은 지리적 위치와 시간대에 따라 다릅니다. UTC는 전 세계적으로 일정합니다.

특징UTC 시간현지 시간
시간대 오프셋항상 UTC+00:00위치에 따라 다름(예: UTC-5, UTC+8, UTC-10)
일광 절약 시간제DST 조정 없음계절과 지역에 따라 다름
일관성전 세계적으로 일관성시스템마다 현지 시간이 다를 수 있습니다
기본 사용 사례글로벌 시스템, 데이터베이스, API사용자 대상 애플리케이션, 캘린더 이벤트
스토리지 크기타임스탬프와 동일(추가 오버헤드 없음)DateTime과 동일(더 큰 저장 공간)
쿼리 성능우수(수치비교)느림(날짜/시간 구문 분석 필요)

경고: 데이터베이스에는 항상 UTC 타임스탬프를 저장하세요. 표시 목적으로만 현지 시간으로 변환합니다.

UTC 타임스탬프 형식

ISO 8601

ISO 8601의 UTC 타임스탬프는 항상 "Z"로 끝납니다.

2025-01-07T12:00:00.000Z  // January 7, 2025, 12:00:00 UTC

유닉스 타임스탬프

UTC 타임스탬프는 Unix 시대(1970-01-01 00:00:00 UTC) 이후의 초 수입니다.

1735689600 // January 1, 2025, 00:00:00 UTC

UTC를 현지 시간으로 변환

자바스크립트

// Convert UTC timestamp (seconds) to local time
function utcToLocal(utcTimestampSeconds, timezoneOffsetHours = 0) {
  const date = new Date(
    (utcTimestampSeconds * 1000) + (timezoneOffsetHours * 60 * 60 * 1000),
  );
  return date.toLocaleString(); // Returns string like "1/7/2025, 6:12:00 PM"
}

// Get UTC timestamp and convert to local
const now = Math.floor(Date.now() / 1000);
console.log(utcToLocal(now, -5)); // UTC-5 for EST

파이썬

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

# Convert UTC to specific timezone
def utc_to_local(utc_timestamp: int, timezone_str: str) -> datetime:
    """
    Convert UTC timestamp to local datetime in specified timezone.

    Args:
        utc_timestamp: Unix timestamp in seconds
        timezone_str: IANA timezone name (e.g., 'America/New_York')

    Returns:
        Local datetime object
    """
    utc_time = datetime.fromtimestamp(utc_timestamp, tz=timezone.utc)
    return utc_time.astimezone(ZoneInfo(timezone_str))

# Example
print(utc_to_local(1735689600, "America/Los_Angeles"))

SQL

-- MySQL: Convert UTC timestamp to datetime
-- Note: Use FROM_UNIXTIME() which respects the system timezone setting

-- Convert UTC timestamp to MySQL DATETIME
SELECT
  id,
  FROM_UNIXTIME(created_at) AS mysql_datetime,
  created_at
FROM events
WHERE id = ?;

-- Store current UTC timestamp
UPDATE events
SET created_at = UNIX_TIMESTAMP(NOW());

-- PostgreSQL: Use TIMESTAMPTZ for timezone-aware storage
CREATE TABLE events (
  id BIGSERIAL PRIMARY KEY,
  event_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  event_date TIMESTAMP WITH TIME ZONE 'UTC'
);

-- Query events with local time display
SELECT
  id,
  event_timestamp,
  TO_CHAR(event_timestamp, 'YYYY-MM-DD HH24:MI:SS') AS local_time
FROM events;

모범 사례: 항상 UTC 타임스탬프를 저장하세요. 표시용으로만 애플리케이션 수준 시간대 변환을 사용합니다.

시간대 처리

시간대 오프셋 이해

시간대 오프셋은 다음과 같이 표현됩니다.

  • UTC+XX:00(예: UTC-5:00)
  • UTC-XX:00(예: UTC+8:00)
오프셋영업시간도시지역
UTC-5:00-5뉴욕, 토론토, 보고타, 리마동부 표준시
UTC-8:00-8로스앤젤레스, 샌프란시스코, 티후아나태평양 표준시
UTC+0:000런던, 더블린, 리스본서부 유럽 시간
UTC+1:00+1파리, 베를린, 로마중앙 유럽 시간
UTC+8:00+8싱가포르, 홍콩, 퍼스중국 표준시
UTC+9:00+9도쿄, 서울, 평양일본 표준시
UTC+10:00+10시드니, 멜버른, 브리즈번호주 동부 표준시
UTC+12:00+12오클랜드뉴질랜드 표준시

시간대 변환 예

JavaScript 시간대 변환

// Convert between UTC and different timezones
function convertToTimezone(utcDate, timezone) {
  const options = { timeZone: timezone };
  return utcDate.toLocaleString('en-US', options);
}

// Examples
const utcDate = new Date('2025-01-07T12:00:00.000Z');

console.log(convertToTimezone(utcDate, 'America/New_York'));    // "1/7/2025, 7:00:00 AM EST"
console.log(convertToTimezone(utcDate, 'Asia/Tokyo'));      // "2025/1/7, 21:00:00 JST"
console.log(convertToTimeDate, 'Europe/London'));     // "1/7/2025, 12:00:00 GMT"
console.log(convertToTimezone(utcDate, 'Asia/Shanghai'));   // "2025/1/7, 20:00:00 CST"
// Python timezone handling
from datetime import datetime, timezone

# Get current UTC time and convert to timezone
now_utc = datetime.now(timezone.utc)

# Convert to specific timezone
now_tokyo = now_utc.astimezone('Asia/Tokyo')
now_est = now_utc.astimezone('America/New_York')
now_gmt = now_utc.astimezone('Etc/GMT')

print(f"UTC: {now_utc}")
print(f"Tokyo: {now_tokyo}")
print(f"EST: {now_est}")
print(f"GMT: {now_gmt}")

모범 사례

UTC 저장 지침

저장: 항상 UTC 타임스탬프를 저장하세요. 시간대에 구애받지 않으며 글로벌 애플리케이션에 효율적입니다.

표시: UI 레이어에서만 현지 시간대로 변환합니다. 현지 시간을 데이터베이스에 다시 저장하지 마십시오.

쿼리: 항상 UTC 타임스탬프를 기준으로 필터링하고 정렬합니다. 이를 통해 사용자의 시간대에 관계없이 일관된 주문이 보장됩니다.

API: API 응답에는 항상 UTC 타임스탬프를 사용하세요. API 문서에 시간대를 기록하세요.

중요 경고: 동일한 열에서 UTC 타임스탬프와 로컬 타임스탬프를 혼합하지 마십시오. 이로 인해 데이터 무결성 문제와 쿼리 불일치가 발생합니다.

일반적인 함정

함정 1: 시간대를 잊어버리는 것

문제: 모든 위치에서 동시에 DST를 관찰하는 것은 아닙니다.

예: 애리조나는 DST를 관찰하지 않지만 뉴욕은 관찰합니다. 이로 인해 특정 기간 동안에는 1시간의 차이가 발생할 수 있습니다.

해결책: 과거 및 현재 DST 규칙을 포함하는 IANA 시간대 데이터베이스(tz 데이터베이스)를 사용합니다.

함정 2: 잘못된 시간대 오프셋

문제: 시간대 이름 대신 하드코딩된 오프셋을 사용합니다.

나쁨: const offset = -5 * 3600000; // EST는 항상 -5이지만 애리조나는 DST를 준수하지 않습니다.

좋음: const offset = 'America/New_York'; // 올바른 과거 DST가 포함된 IANA 데이터베이스를 사용합니다.

함정 3: 모든 시간이 동일한 형식이라고 가정

문제: 모든 시스템이 UTC를 사용하는 것은 아닙니다(예: 일부 시스템은 GMT를 사용하고 다른 시스템은 UTC+X를 사용합니다).

예: Unix 타임스탬프는 항상 UTC 기반이지만 파일 시스템은 다를 수 있습니다.

해결책: 사용자 입력을 구문 분석할 때 항상 시간대를 명시적으로 지정하세요.

다른 시간대를 사용한 작업

자바스크립트

// Best practice: Always specify timezone when creating dates
const date1 = new Date('2025-01-07T12:00:00'); // UTC time (good)

const date2 = new Date('2025-01-07T12:00:00-08:00'); // Bad: assumes local timezone

// Convert between timezones
function convertTimezones(fromDate, fromTz, toTz) {
  return {
    fromTime: fromDate.toLocaleString('en-US', { timeZone: fromTz }),
    toTime: fromDate.toLocaleString('en-US', { timeZone: toTz }),
    fromTimestamp: fromDate.getTime(),
    toTimestamp: fromDate.toLocaleString('en-US', { timeZone: toTz }),
  };
}

// Example: Convert UTC to multiple timezones
const utcDate = new Date('2025-01-07T12:00:00.000Z');
const conversions = [
  convertTimezones(utcDate, 'UTC', 'America/New_York'),
  convertTimezones(utcDate, 'UTC', 'Asia/Tokyo'),
  convertTimezones(utcDate, 'UTC', 'Europe/London'),
];

파이썬

from datetime import datetime, timezone

# Best practice: Use pytz library
import pytz

def convert_to_timezone(utc_time: datetime, timezone: str) -> datetime:
    """
    Convert UTC datetime to specified timezone using IANA timezone database.

    Args:
        utc_time: UTC datetime object
        timezone_str: IANA timezone name

    Returns:
        Localized datetime object
    """
    utc_time = utc_time.replace(tzinfo=timezone.tzinfo(utc_time))
    return utc_time.astimezone(timezone)

# Example: Convert current UTC to multiple timezones
now_utc = datetime.now(timezone.utc)
now_est = now_utc.astimezone('America/New_York')
now_gmt = now_utc.astimezone('Etc/GMT')
now_tokyo = now_utc.astimezone('Asia/Tokyo')

print(f"UTC: {now_utc}")
print(f"EST: {now_est}")
print(f"GMT: {now_gmt}")
print(f"JST: {now_tokyo}")

시간대 모범 사례

시간대 선택 지침

<올>

<li>항상 IANA 시간대 이름을 사용하세요(예: "America/New_York", "Europe/London")</li> <li>하드코딩된 오프셋 대신 시간대 데이터베이스(IANA tz 데이터베이스, tz 데이터베이스) 사용</li> <li>대상 지역(특히 봄과 가을)에서 DST 전환을 테스트하세요.</li> <li>API 문서에 시간대 가정을 명확하게 문서화하세요.</li> <li>모든 내부 저장 및 계산에 UTC 사용을 고려하세요</li> <li>UI에 시간대 이름과 현지 시간을 별도로 표시합니다(내부적으로 UTC 저장)</li> </ol>

도구 및 참고자료

관련 도구

요약

주요 내용: 항상 UTC 타임스탬프를 저장하세요. 애플리케이션 또는 쿼리 계층에서 시간대 변환을 처리합니다. 이를 통해 데이터 일관성이 보장되고 애플리케이션이 전 세계적으로 호환됩니다.

중요: 데이터베이스 저장소에서 UTC와 로컬 타임스탬프를 혼합하지 마십시오. 항상 UTC를 저장하고 필요할 때만 로컬로 변환하십시오.

성능 팁: UTC 타임스탬프는 다음에 이상적입니다.

  • 데이터베이스 인덱싱(숫자 비교)
  • 범위 쿼리(숫자 필터)
  • 정렬 작업(숫자순)
  • 시간 기반 파티셔닝

코드 예제 저장소

더 많은 타임스탬프 및 시간대 코드 예제를 보려면 특정 사용 사례 작업에 대한 관련 도구 및 가이드를 참조하세요.