2025.7.2 수요일의 공부기록
이번 글에서는 JavaScript의 국제화(Intl) API 중 하나인 Intl.RelativeTimeFormat
를 이용해 날짜와 시간을 상대적 표현(예: 3일 전, 2시간 후)으로 포맷하는 방법과 숫자 표현을 위한 toLocaleString 메서드를 함께 자세히 알아보자.
Intl.RelativeTimeFormat
는 JavaScript의 국제화 API로, 현재 시간과 주어진 시간을 상대적으로 표현할 때 사용된다.
예를 들어, 다음과 같이 손쉽게 표현할 수 있다:
const rtf = new Intl.RelativeTimeFormat("ko-KR");
console.log(rtf.format(-3, "days")); // "3일 전"
console.log(rtf.format(2, "hours")); // "2시간 후"
Intl.RelativeTimeFormat
는 두 가지 주요 옵션을 지원한다:
numeric
: 숫자 표현 방식을 설정 (auto/numeric)style
: 출력 스타일 선택 (long/short/narrow)예시 코드:
const rtf = new Intl.RelativeTimeFormat("ko-KR", {
numeric: "auto", // auto: "어제"와 같이 표현, numeric: 항상 숫자 표기
style: "long", // "3일 전", "3 days ago"
});
console.log(rtf.format(-1, "days")); // "어제"
console.log(rtf.format(1, "days")); // "내일"
const rtf = new Intl.RelativeTimeFormat("ko-KR", { numeric: "auto" });
rtf.format(-1, "days"); // 어제
rtf.format(-5, "days"); // 5일 전
rtf.format(0, "days"); // 오늘
rtf.format(3, "days"); // 3일 후
rtf.format(1, "weeks"); // 다음 주
rtf.format(-2, "months");// 2개월 전
Intl.RelativeTimeFormat
는 다양한 시간 단위를 지원한다:
year
: 년quarter
: 분기 (3개월)month
: 월week
: 주day
: 일hour
: 시간minute
: 분second
: 초예시:
const rtf = new Intl.RelativeTimeFormat("ko-KR", { numeric: "auto" });
console.log(rtf.format(-1, "week")); // 지난주
console.log(rtf.format(2, "month")); // 2개월 후
toLocaleString
JavaScript의 toLocaleString
메서드는 숫자를 국제화 표준에 맞춰 쉽게 포맷팅하는 기능을 제공한다.
가격이나 화폐와 같이 숫자를 통화 단위로 표현할 때 매우 유용하다.
const price = 10000;
console.log(price.toLocaleString("ko-KR")); // "10,000"
통화 형태로 숫자를 표현하려면 style: "currency"
와 currency
옵션을 설정하면 된다.
const price = 50000;
console.log(price.toLocaleString("ko-KR", {
style: "currency",
currency: "KRW"
})); // "₩50,000"
옵션 | 설명 | 예시 |
---|---|---|
style | 숫자 표현 방식을 결정 (decimal, currency, percent 등) | "currency" |
currency | 통화 단위 지정 (KRW, USD 등) | "KRW" |
minimumFractionDigits | 최소 소수점 자릿수 지정 | 2 (10.00) |
maximumFractionDigits | 최대 소수점 자릿수 지정 | 2 (10.25) |
// util.ts
export const formatToWon = (price: number): string => {
return price.toLocaleString("ko-KR", {
style: "currency",
currency: "KRW",
});
};
console.log(formatToWon(1500000)); // ₩1,500,000
이러한 방식으로 숫자 값을 한국 사용자에게 친숙한 한화 표기로 간단히 변환할 수 있다.
// util.ts
export const formatToWon = (price: number): string => {
return price.toLocaleString("ko-KR", {
style: "currency",
currency: "KRW",
});
};
export const formatToDate = (date: Date): string => {
const dayInMs = 1000 * 60 * 60 * 24; // 하루를 밀리초로 변환
const time = new Date(date).getTime(); // 주어진 날짜를 밀리초로 변환
const now = new Date().getTime(); // 현재 시간을 밀리초로 변환
const diff = Math.round((time - now) / dayInMs); // 두 날짜의 차이 계산 (일 단위)
const formattedDate = new Intl.RelativeTimeFormat("ko-KR", {
numeric: "auto", // 자연스러운 표현 (어제, 오늘 등)
});
return formattedDate.format(diff, "days");
};
formatToWon
: 숫자를 한화(₩) 통화 형태로 변환하는 함수다.formatToDate
: 날짜를 상대적인 시간 표현으로 변환하는 함수다.Next.js 15 버전 이상에서는 동적 라우팅에서 params
를 가져올 때 반드시 await
를 앞에 붙여 사용해야 한다.
예시:
// Next.js 15에서 올바른 사용법
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
return <div>현재 페이지의 ID: {id}</div>;
}