Intl.RelativeTimeFormat 과 toLocaleString 이용한 상대 표현

Odyssey·2025년 7월 1일
0

Next.js_study

목록 보기
52/58
post-thumbnail

2025.7.2 수요일의 공부기록

이번 글에서는 JavaScript의 국제화(Intl) API 중 하나인 Intl.RelativeTimeFormat를 이용해 날짜와 시간을 상대적 표현(예: 3일 전, 2시간 후)으로 포맷하는 방법과 숫자 표현을 위한 toLocaleString 메서드를 함께 자세히 알아보자.


Intl.RelativeTimeFormat란?

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시간 후"

🔗 MDN 공식 문서


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개월 전

사용 가능한 시간 단위 (unit)

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)

🔗 MDN 공식 문서

예시

가격을 한화(₩) 형식으로 변환

// 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: 날짜를 상대적인 시간 표현으로 변환하는 함수다.
    • 날짜 차이를 밀리초로 계산하여 이를 일 단위로 변환한다.
    • 이를 통해 "어제", "오늘", "내일", "3일 후"와 같이 표현할 수 있다.

[추가] Next.js 15에서 동적 라우팅 시 변경 사항

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>;
}

🔗 Next.js 공식 문서 (Dynamic Routes)

0개의 댓글