Tutorial
JavaScript에서 타임스탬프를 변환하는 방법: 예제가 포함된 완전한 튜토리얼
소개
JavaScript에서 타임스탬프를 변환하는 것은 웹 개발자의 기본 기술입니다. API, 데이터베이스 또는 사용자 인터페이스를 사용하여 작업하는 경우 Unix 타임스탬프와 사람이 읽을 수 있는 날짜 간에 변환해야 하는 경우가 많습니다. 이 튜토리얼은 여러분이 알아야 할 모든 것을 안내합니다.
무엇을 배울 것인가
- ✅ 현재 타임스탬프 가져오기
- ✅ 타임스탬프를 날짜 객체로 변환
- ✅ 날짜 객체를 타임스탬프로 변환
- ✅ 표시용 타임스탬프 형식 지정
- ✅ 다양한 타임스탬프 정밀도 처리
- ✅ 시간대 작업
- ✅ 일반적인 함정과 이를 피하는 방법
전제 조건
기본 JavaScript 지식만 있으면 됩니다. 이 튜토리얼에는 외부 라이브러리가 필요하지 않습니다(몇 가지 인기 있는 라이브러리는 마지막에 언급하겠지만).
1단계: 현재 타임스탬프 가져오기
가장 간단한 작업은 현재 시간을 타임스탬프로 가져오는 것입니다.
방법 1: Date.now() (권장)
// Get current timestamp in milliseconds
const timestamp = Date.now();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
이것을 사용하는 이유는 무엇입니까?
- ✅ 가장 빠른 방법
- ✅ Date 객체를 생성할 필요가 없습니다.
- ✅ 가장 일반적으로 사용되는
방법 2: new Date().getTime()
// Create Date object and get timestamp
const timestamp = new Date().getTime();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
언제 사용하나요?
- 이미 Date 객체가 있는 경우
- 메소드를 연결해야 하는 경우
방법 3: 단항 더하기 연산자
// Shorthand using unary plus
const timestamp = +new Date();
console.log(timestamp);
// Output: 1704067200000 (13 digits)
언제 사용하나요?
- 코드 골프 또는 간결성이 중요한 경우
- 초보자에게는 권장하지 않음(가독성이 낮음)
초 단위로 타임스탬프 얻기
JavaScript는 기본적으로 밀리초를 사용하지만 많은 API는 초를 사용합니다.
// Get timestamp in seconds (10 digits)
const timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds);
// Output: 1704067200 (10 digits)
// Alternative: Using parseInt
const timestampSec = parseInt(Date.now() / 1000);
console.log(timestampSec);
// Output: 1704067200
2단계: 타임스탬프를 날짜로 변환
Unix 타임스탬프를 JavaScript Date 객체로 변환합니다.
기본 변환
// Millisecond timestamp (13 digits)
const timestamp = 1704067200000;
const date = new Date(timestamp);
console.log(date);
// Output: Mon Jan 01 2024 00:00:00 GMT+0000 (UTC)
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z
두 번째 타임스탬프 변환
많은 API는 밀리초가 아닌 초(10자리) 단위로 타임스탬프를 반환합니다.
// Second timestamp (10 digits) - MUST multiply by 1000!
const timestampInSeconds = 1704067200;
const date = new Date(timestampInSeconds * 1000);
console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z
⚠️ 일반적인 실수:
// ❌ WRONG: Using seconds directly
const wrongDate = new Date(1704067200);
console.log(wrongDate.toISOString());
// Output: 1970-01-20T17:27:47.200Z (WRONG!)
// ✅ CORRECT: Multiply by 1000
const correctDate = new Date(1704067200 * 1000);
console.log(correctDate.toISOString());
// Output: 2024-01-01T00:00:00.000Z (CORRECT!)
타임스탬프 정밀도 감지
타임스탬프가 초 또는 밀리초 단위인지 자동으로 감지하는 도우미 기능:
function createDateFromTimestamp(timestamp) {
// If timestamp has 10 digits, it's in seconds
// If timestamp has 13 digits, it's in milliseconds
const digitCount = timestamp.toString().length;
if (digitCount === 10) {
// Seconds - multiply by 1000
return new Date(timestamp * 1000);
} else if (digitCount === 13) {
// Milliseconds - use directly
return new Date(timestamp);
} else {
throw new Error(`Invalid timestamp: ${timestamp}`);
}
}
// Usage
const date1 = createDateFromTimestamp(1704067200); // 10 digits (seconds)
const date2 = createDateFromTimestamp(1704067200000); // 13 digits (milliseconds)
console.log(date1.toISOString()); // 2024-01-01T00:00:00.000Z
console.log(date2.toISOString()); // 2024-01-01T00:00:00.000Z
3단계: 날짜를 타임스탬프로 변환
JavaScript Date 객체를 Unix 타임스탬프로 다시 변환합니다.
현재 날짜부터
const now = new Date();
// Get timestamp in milliseconds
const timestampMs = now.getTime();
console.log(timestampMs); // 1704067200000
// Get timestamp in seconds
const timestampSec = Math.floor(now.getTime() / 1000);
console.log(timestampSec); // 1704067200
특정 날짜 문자열에서
// ISO 8601 format (recommended)
const date1 = new Date('2024-01-01T00:00:00Z');
console.log(date1.getTime()); // 1704067200000
// Different date formats
const date2 = new Date('January 1, 2024');
const date3 = new Date('01/01/2024');
const date4 = new Date('2024-01-01');
console.log(date2.getTime()); // Depends on local timezone
console.log(date3.getTime()); // Depends on local timezone
console.log(date4.getTime()); // Usually 00:00:00 in local timezone
⚠️ 중요: 다양한 날짜 문자열 형식은 시간대에 따라 다르게 작동합니다!
날짜 구성 요소에서
// Create date from year, month, day, etc.
// Note: Month is 0-indexed (0 = January, 11 = December)
const date = new Date(2024, 0, 1, 0, 0, 0); // Jan 1, 2024, 00:00:00
const timestamp = date.getTime();
console.log(timestamp); // Local timezone timestamp
// For UTC, use Date.UTC()
const utcTimestamp = Date.UTC(2024, 0, 1, 0, 0, 0);
console.log(utcTimestamp); // 1704067200000 (UTC)
4단계: 타임스탬프 형식 지정
타임스탬프를 사람이 읽을 수 있는 형식으로 변환합니다.
내장 JavaScript 메소드
const date = new Date(1704067200000);
// ISO 8601 format (best for APIs)
console.log(date.toISOString());
// Output: "2024-01-01T00:00:00.000Z"
// Locale-specific date string
console.log(date.toLocaleDateString());
// Output: "1/1/2024" (US) or "01/01/2024" (UK)
// Locale-specific date and time
console.log(date.toLocaleString());
// Output: "1/1/2024, 12:00:00 AM"
// Locale-specific time
console.log(date.toLocaleTimeString());
// Output: "12:00:00 AM"
// Full date string
console.log(date.toDateString());
// Output: "Mon Jan 01 2024"
// UTC string
console.log(date.toUTCString());
// Output: "Mon, 01 Jan 2024 00:00:00 GMT"
사용자 정의 형식
function formatTimestamp(timestamp, format = 'full') {
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
const formats = {
'full': `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
'date': `${year}-${month}-${day}`,
'time': `${hours}:${minutes}:${seconds}`,
'short': `${month}/${day}/${year}`,
'iso': date.toISOString()
};
return formats[format] || formats.full;
}
// Usage
const timestamp = 1704067200000;
console.log(formatTimestamp(timestamp, 'full')); // "2024-01-01 00:00:00"
console.log(formatTimestamp(timestamp, 'date')); // "2024-01-01"
console.log(formatTimestamp(timestamp, 'time')); // "00:00:00"
console.log(formatTimestamp(timestamp, 'short')); // "01/01/2024"
Intl.DateTimeFormat 사용(최신 접근 방식)
const timestamp = 1704067200000;
const date = new Date(timestamp);
// US English format
const usFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
console.log(usFormatter.format(date));
// Output: "January 1, 2024 at 12:00 AM"
// Custom format
const customFormatter = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
console.log(customFormatter.format(date));
// Output: "Monday, Jan 1, 2024, 12:00:00 AM UTC"
5단계: 시간대 작업
정확한 타임스탬프 변환을 위해서는 다양한 시간대를 처리하는 것이 중요합니다.
UTC와 현지 시간
const timestamp = 1704067200000; // Jan 1, 2024, 00:00:00 UTC
const date = new Date(timestamp);
// Get UTC components
console.log('UTC Year:', date.getUTCFullYear()); // 2024
console.log('UTC Month:', date.getUTCMonth() + 1); // 1
console.log('UTC Date:', date.getUTCDate()); // 1
console.log('UTC Hours:', date.getUTCHours()); // 0
// Get local components (depends on your timezone)
console.log('Local Year:', date.getFullYear()); // 2024
console.log('Local Month:', date.getMonth() + 1); // 1 (or different)
console.log('Local Date:', date.getDate()); // 1 (or different)
console.log('Local Hours:', date.getHours()); // 0 (or different)
특정 시간대로 변환
const timestamp = 1704067200000;
const date = new Date(timestamp);
// Display in different timezones using Intl.DateTimeFormat
const timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo'];
timezones.forEach(tz => {
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
});
console.log(`${tz}:`, formatter.format(date));
});
// Output:
// America/New_York: 12/31/2023, 07:00:00 PM EST
// Europe/London: 01/01/2024, 12:00:00 AM GMT
// Asia/Tokyo: 01/01/2024, 09:00:00 AM JST
시간대 오프셋
const date = new Date();
// Get timezone offset in minutes
const offsetMinutes = date.getTimezoneOffset();
console.log('Offset in minutes:', offsetMinutes); // e.g., -480 for UTC+8
// Convert to hours
const offsetHours = -offsetMinutes / 60;
console.log('Offset in hours:', offsetHours); // e.g., 8 for UTC+8
// Format offset as string
const sign = offsetHours >= 0 ? '+' : '-';
const hours = String(Math.abs(Math.floor(offsetHours))).padStart(2, '0');
const minutes = String(Math.abs((offsetHours % 1) * 60)).padStart(2, '0');
console.log(`UTC${sign}${hours}:${minutes}`); // e.g., "UTC+08:00"
6단계: 일반적인 함정 및 해결 방법
함정 1: 초 대 밀리초
// ❌ WRONG: Assuming all timestamps are in milliseconds
const wrongDate = new Date(1704067200); // Treats as milliseconds
console.log(wrongDate.toISOString()); // 1970-01-20T17:27:47.200Z (WRONG!)
// ✅ CORRECT: Check and convert properly
const secondsTimestamp = 1704067200;
const correctDate = new Date(secondsTimestamp * 1000);
console.log(correctDate.toISOString()); // 2024-01-01T00:00:00.000Z (CORRECT!)
함정 2: 달의 색인이 0입니다.
// ❌ WRONG: Using 1-12 for months
const wrongDate = new Date(2024, 1, 1); // Creates Feb 1, not Jan 1
console.log(wrongDate.toDateString()); // Thu Feb 01 2024
// ✅ CORRECT: Use 0-11 for months
const correctDate = new Date(2024, 0, 1); // Creates Jan 1
console.log(correctDate.toDateString()); // Mon Jan 01 2024
함정 3: 날짜 문자열의 시간대 문제
// Different string formats behave differently!
// ISO 8601 with 'Z' - always UTC
const utcDate = new Date('2024-01-01T00:00:00Z');
console.log(utcDate.toISOString()); // 2024-01-01T00:00:00.000Z
// ISO 8601 without 'Z' - treated as local timezone
const localDate = new Date('2024-01-01T00:00:00');
console.log(localDate.toISOString()); // Depends on your timezone
// Date-only format - treated as local timezone at midnight
const dateOnly = new Date('2024-01-01');
console.log(dateOnly.toISOString()); // Usually local midnight
// ✅ BEST PRACTICE: Always use ISO 8601 with 'Z' for UTC
const safeDate = new Date('2024-01-01T00:00:00.000Z');
함정 4: 잘못된 날짜
// Invalid dates can cause silent errors
const invalidDate = new Date('not a date');
console.log(invalidDate); // Invalid Date
console.log(invalidDate.getTime()); // NaN
// ✅ BEST PRACTICE: Always validate
function isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
const date1 = new Date('2024-01-01');
const date2 = new Date('invalid');
console.log(isValidDate(date1)); // true
console.log(isValidDate(date2)); // false
7단계: 실제 예
예 1: "시간 전" 형식 표시
function timeAgo(timestamp) {
const now = Date.now();
const secondsAgo = Math.floor((now - timestamp) / 1000);
if (secondsAgo < 60) {
return `${secondsAgo} seconds ago`;
} else if (secondsAgo < 3600) {
const minutes = Math.floor(secondsAgo / 60);
return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
} else if (secondsAgo < 86400) {
const hours = Math.floor(secondsAgo / 3600);
return `${hours} hour${hours > 1 ? 's' : ''} ago`;
} else {
const days = Math.floor(secondsAgo / 86400);
return `${days} day${days > 1 ? 's' : ''} ago`;
}
}
// Usage
console.log(timeAgo(Date.now() - 30000)); // "30 seconds ago"
console.log(timeAgo(Date.now() - 300000)); // "5 minutes ago"
console.log(timeAgo(Date.now() - 7200000)); // "2 hours ago"
console.log(timeAgo(Date.now() - 172800000)); // "2 days ago"
예시 2: API 응답 핸들러
// Typical API response with timestamps
const apiResponse = {
created_at: 1704067200, // Seconds
updated_at: 1704153600000, // Milliseconds (mixed precision!)
expires_at: "2024-01-10T00:00:00Z" // ISO 8601 string
};
// Convert all to Date objects
function parseApiTimestamps(response) {
return {
created: new Date(response.created_at * 1000), // Convert seconds
updated: new Date(response.updated_at), // Already milliseconds
expires: new Date(response.expires_at) // Parse ISO string
};
}
const dates = parseApiTimestamps(apiResponse);
console.log('Created:', dates.created.toLocaleDateString());
console.log('Updated:', dates.updated.toLocaleDateString());
console.log('Expires:', dates.expires.toLocaleDateString());
예 3: 날짜 범위 검사기
function isWithinRange(timestamp, startDate, endDate) {
const date = new Date(timestamp);
const start = new Date(startDate);
const end = new Date(endDate);
return date >= start && date <= end;
}
// Usage
const eventTimestamp = 1704067200000; // Jan 1, 2024
const rangeStart = '2024-01-01';
const rangeEnd = '2024-12-31';
console.log(isWithinRange(eventTimestamp, rangeStart, rangeEnd)); // true
고급 사용 사례를 위한 인기 라이브러리
프로덕션 애플리케이션의 경우 다음 라이브러리를 고려하세요.
date-fns(권장)
import { format, parseISO, formatDistance } from 'date-fns';
// Format timestamp
const timestamp = 1704067200000;
const formatted = format(timestamp, 'PPP');
console.log(formatted); // "Jan 1st, 2024"
// Time ago
const distance = formatDistance(timestamp, Date.now(), { addSuffix: true });
console.log(distance); // "2 days ago"
Luxon(현대, 시간대 인식)
import { DateTime } from 'luxon';
// From timestamp
const dt = DateTime.fromMillis(1704067200000);
console.log(dt.toISO()); // "2024-01-01T00:00:00.000Z"
// Timezone conversion
const tokyo = dt.setZone('Asia/Tokyo');
console.log(tokyo.toFormat('yyyy-MM-dd HH:mm:ss'));
요약
다음 방법을 배웠습니다.
- ✅
Date.now()를 사용하여 현재 타임스탬프를 가져옵니다. - ✅ 타임스탬프를 날짜 객체로 변환
- ✅ 날짜 객체를 다시 타임스탬프로 변환
- ✅ 표시 날짜 형식
- ✅ 다양한 타임스탬프 정밀도 처리
- ✅ 시간대 작업
- ✅ 일반적인 함정을 피하세요
관련 도구
무료 도구를 사용하여 배운 내용을 연습해 보세요.
- Unix 타임스탬프 변환기 - 대화형 타임스탬프 변환
- 현재 타임스탬프 - 현재 시간을 다양한 형식으로 가져옵니다.
- JavaScript 타임스탬프 도우미 - JavaScript 전용 도구
- 일괄 타임스탬프 변환기 - 여러 타임스탬프 변환
다음 단계
- 타임스탬프 정밀도 수준에 대해 알아보세요.
- 시간대 이해 살펴보기
- 2038년 문제에 대해 읽어보세요.
최종 업데이트: 2025년 1월