'3일 전' 또는 '2시간 후'와 같은 상대적 시간을 어떻게 형식화하나요?

Intl.RelativeTimeFormat를 사용하여 '3일 전' 또는 '2시간 후'와 같은 시간을 자동 복수화 및 현지화와 함께 모든 언어로 표시합니다

소개

소셜 미디어 피드, 댓글 섹션, 활동 로그에는 "5분 전", "2시간 전" 또는 "3일 후"와 같은 상대적 시간 표시가 표시됩니다. 이러한 상대적 타임스탬프는 사용자가 절대 날짜를 분석할 필요 없이 언제 무언가가 발생했는지 빠르게 이해하는 데 도움이 됩니다.

이러한 문자열을 영어로 하드코딩하면 모든 사용자가 영어를 사용하고 영어 문법 규칙을 따른다고 가정하게 됩니다. 다른 언어는 상대적 시간을 표현하는 방식이 다릅니다. 스페인어는 "3 days ago" 대신 "hace 3 días"라고 말합니다. 일본어는 완전히 다른 구조로 "3日前"를 사용합니다. 각 언어에는 또한 단수형과 복수형을 사용할 때를 결정하는 고유한 복수화 규칙이 있습니다.

JavaScript는 Intl.RelativeTimeFormat API를 제공하여 상대적 시간 형식을 자동으로 처리합니다. 이 수업에서는 이 내장 API를 사용하여 모든 언어에 대해 상대적 시간을 올바르게 형식화하는 방법을 설명합니다.

상대적 시간 형식이 국제화를 필요로 하는 이유

다른 언어는 상대적 시간을 다른 방식으로 표현합니다. 영어는 과거 시간에 대해서는 시간 단위를 "ago" 앞에 배치하고 미래 시간에 대해서는 "in" 뒤에 배치합니다. 다른 언어는 다른 단어 순서, 다른 전치사 또는 완전히 다른 문법 구조를 사용합니다.

const rtfEnglish = new Intl.RelativeTimeFormat('en');
console.log(rtfEnglish.format(-3, 'day'));
// "3 days ago"

const rtfSpanish = new Intl.RelativeTimeFormat('es');
console.log(rtfSpanish.format(-3, 'day'));
// "hace 3 días"

const rtfJapanese = new Intl.RelativeTimeFormat('ja');
console.log(rtfJapanese.format(-3, 'day'));
// "3 日前"

각 언어는 자체 규칙을 따르는 자연스러운 출력을 생성합니다. 이러한 규칙을 알거나 번역 파일을 유지할 필요가 없습니다. API가 모든 형식 지정 세부 사항을 자동으로 처리합니다.

복수화 규칙도 언어마다 크게 다릅니다. 영어는 "1 day"와 "2 days"를 구분합니다. 아랍어는 개수에 따라 여섯 가지 다른 복수형을 가집니다. 일본어는 수량에 관계없이 동일한 형태를 사용합니다. Intl.RelativeTimeFormat API는 각 언어에 맞는 올바른 복수화 규칙을 적용합니다.

Intl.RelativeTimeFormat API

'Intl.RelativeTimeFormat' 생성자는 숫자 값과 시간 단위를 현지화된 문자열로 변환하는 포맷터를 생성합니다. 첫 번째 인수로 로케일 식별자를 전달한 다음, 'format()' 메서드를 값과 단위와 함께 호출합니다.

const rtf = new Intl.RelativeTimeFormat('en-US');

console.log(rtf.format(-1, 'day'));
// "1 day ago"

console.log(rtf.format(2, 'hour'));
// "in 2 hours"

'format()' 메서드는 두 개의 매개변수를 받습니다. 첫 번째는 시간의 양을 나타내는 숫자입니다. 두 번째는 시간 단위를 지정하는 문자열입니다.

음수는 과거 시간을 나타내고, 양수는 미래 시간을 나타냅니다. 이 규칙은 부호 규칙을 이해하면 API를 직관적으로 사용할 수 있게 해줍니다.

과거 및 미래 시간 포맷팅

값의 부호는 시간이 과거인지 미래인지를 결정합니다. 음수 값은 과거 시제를 생성하고, 양수 값은 미래 시제를 생성합니다.

const rtf = new Intl.RelativeTimeFormat('en-US');

console.log(rtf.format(-5, 'minute'));
// "5 minutes ago"

console.log(rtf.format(5, 'minute'));
// "in 5 minutes"

console.log(rtf.format(-2, 'week'));
// "2 weeks ago"

console.log(rtf.format(2, 'week'));
// "in 2 weeks"

이 패턴은 모든 시간 단위와 모든 언어에서 일관되게 작동합니다. API는 값이 양수인지 음수인지에 따라 올바른 문법 구조를 자동으로 선택합니다.

사용 가능한 시간 단위

API는 대부분의 상대적 시간 포맷팅 요구를 충족하는 8개의 시간 단위를 지원합니다. 단수형이나 복수형을 사용할 수 있으며, 둘 다 동일하게 작동합니다.

const rtf = new Intl.RelativeTimeFormat('en-US');

console.log(rtf.format(-30, 'second'));
// "30 seconds ago"

console.log(rtf.format(-15, 'minute'));
// "15 minutes ago"

console.log(rtf.format(-6, 'hour'));
// "6 hours ago"

console.log(rtf.format(-3, 'day'));
// "3 days ago"

console.log(rtf.format(-2, 'week'));
// "2 weeks ago"

console.log(rtf.format(-4, 'month'));
// "4 months ago"

console.log(rtf.format(-1, 'quarter'));
// "1 quarter ago"

console.log(rtf.format(-2, 'year'));
// "2 years ago"

API는 'day'와 같은 단수형과 'days'와 같은 복수형을 모두 허용합니다. 둘 다 동일한 출력을 생성합니다. 분기(quarter) 단위는 회계 기간을 다루는 비즈니스 애플리케이션에 유용합니다.

numeric auto를 사용한 자연어 표현

numeric 옵션은 포맷터가 숫자를 사용할지 자연어 대안을 사용할지 제어합니다. 기본값은 always로, 항상 숫자를 표시합니다.

const rtfAlways = new Intl.RelativeTimeFormat('en-US', {
  numeric: 'always'
});

console.log(rtfAlways.format(-1, 'day'));
// "1 day ago"

console.log(rtfAlways.format(0, 'day'));
// "in 0 days"

console.log(rtfAlways.format(1, 'day'));
// "in 1 day"

numericauto로 설정하면 특정 값에 대해 더 자연스러운 표현이 생성됩니다.

const rtfAuto = new Intl.RelativeTimeFormat('en-US', {
  numeric: 'auto'
});

console.log(rtfAuto.format(-1, 'day'));
// "yesterday"

console.log(rtfAuto.format(0, 'day'));
// "today"

console.log(rtfAuto.format(1, 'day'));
// "tomorrow"

이 옵션은 인터페이스를 더 대화적으로 만듭니다. 사용자는 "1 day ago" 대신 "yesterday"를 보게 되어 더 자연스럽게 읽힙니다. auto 옵션은 모든 시간 단위와 모든 언어에서 작동하며, 각 언어는 자체적인 관용적 대안을 제공합니다.

포맷팅 스타일 선택

style 옵션은 출력의 상세도를 제어합니다. 사용 가능한 세 가지 스타일은 long, short, narrow입니다.

const rtfLong = new Intl.RelativeTimeFormat('en-US', {
  style: 'long'
});
console.log(rtfLong.format(-2, 'hour'));
// "2 hours ago"

const rtfShort = new Intl.RelativeTimeFormat('en-US', {
  style: 'short'
});
console.log(rtfShort.format(-2, 'hour'));
// "2 hr. ago"

const rtfNarrow = new Intl.RelativeTimeFormat('en-US', {
  style: 'narrow'
});
console.log(rtfNarrow.format(-2, 'hour'));
// "2h ago"

long 스타일이 기본값이며 대부분의 인터페이스에 적합합니다. short 스타일은 모바일 레이아웃이나 테이블에서 공간을 절약합니다. narrow 스타일은 공간이 극도로 제한된 디자인을 위한 가장 간결한 출력을 생성합니다.

시간 차이 계산

Intl.RelativeTimeFormat API는 값을 포맷팅하지만 계산하지는 않습니다. 시간 차이를 직접 계산한 다음 결과를 포맷터에 전달해야 합니다.

시간 차이를 계산하려면 현재 날짜에서 대상 날짜를 빼고, 결과를 밀리초에서 원하는 단위로 변환합니다.

const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });

function formatDaysAgo(date) {
  const now = new Date();
  const diffInMs = date - now;
  const diffInDays = Math.round(diffInMs / (1000 * 60 * 60 * 24));

  return rtf.format(diffInDays, 'day');
}

const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

console.log(formatDaysAgo(yesterday));
// "yesterday"

const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

console.log(formatDaysAgo(tomorrow));
// "tomorrow"

이 함수는 대상 날짜와 현재 시간 사이의 일 수 차이를 계산합니다. 계산은 밀리초를 하루의 밀리초 수로 나눈 다음 가장 가까운 정수로 반올림합니다.

date - now 뺄셈은 과거 날짜에 대해서는 음수 값을, 미래 날짜에 대해서는 양수 값을 생성합니다. 이는 format() 메서드가 예상하는 부호 규칙과 일치합니다.

완전한 유틸리티 함수 구축하기

범용적인 상대 시간 포맷터를 위해서는 시간 차이의 크기에 따라 가장 적절한 시간 단위를 선택해야 합니다.

const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });

const units = {
  year: 24 * 60 * 60 * 1000 * 365,
  month: 24 * 60 * 60 * 1000 * 365 / 12,
  week: 24 * 60 * 60 * 1000 * 7,
  day: 24 * 60 * 60 * 1000,
  hour: 60 * 60 * 1000,
  minute: 60 * 1000,
  second: 1000
};

function formatRelativeTime(date) {
  const now = new Date();
  const diffInMs = date - now;
  const absDiff = Math.abs(diffInMs);

  for (const [unit, msValue] of Object.entries(units)) {
    if (absDiff >= msValue || unit === 'second') {
      const value = Math.round(diffInMs / msValue);
      return rtf.format(value, unit);
    }
  }
}

const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000);
console.log(formatRelativeTime(fiveMinutesAgo));
// "5 minutes ago"

const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
console.log(formatRelativeTime(threeDaysAgo));
// "3 days ago"

const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000);
console.log(formatRelativeTime(tomorrow));
// "tomorrow"

이 함수는 가장 큰 단위부터 가장 작은 단위까지 시간 단위를 반복하면서, 절대 차이가 해당 단위의 밀리초 값을 초과하는 첫 번째 단위를 선택합니다. 초 단위로의 폴백은 함수가 항상 결과를 반환하도록 보장합니다.

단위 정의는 근사값을 사용합니다. 월은 다양한 월의 길이를 고려하는 대신 1년의 1/12로 계산됩니다. 이러한 근사치는 정확한 정밀도보다 대략적인 값이 더 유용한 상대 시간 표시에 적합합니다.

사용자의 로케일에 맞는 형식 지정

특정 로케일을 하드코딩하는 대신, 브라우저에서 사용자가 선호하는 언어를 사용할 수 있습니다.

const userLocale = navigator.language;
const rtf = new Intl.RelativeTimeFormat(userLocale, { numeric: 'auto' });

const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);
console.log(rtf.format(-1, 'day'));
// 사용자의 로케일에 따라 출력이 달라짐
// en-US의 경우: "yesterday"
// es-ES의 경우: "ayer"
// fr-FR의 경우: "hier"
// de-DE의 경우: "gestern"

이 접근 방식은 수동으로 로케일을 선택할 필요 없이 각 사용자의 언어 환경 설정에 따라 상대적 시간을 표시합니다. 브라우저가 언어 환경 설정을 제공하고, API가 적절한 형식 지정 규칙을 적용합니다.

다양한 언어로 동일한 시간 보기

동일한 상대 시간 값이 다른 로케일에 따라 다른 출력을 생성합니다. 각 언어는 단어 순서, 문법 및 복수형에 대한 고유한 규칙을 따릅니다.

const threeDaysAgo = -3;

const rtfEnglish = new Intl.RelativeTimeFormat('en-US');
console.log(rtfEnglish.format(threeDaysAgo, 'day'));
// "3 days ago"

const rtfSpanish = new Intl.RelativeTimeFormat('es-ES');
console.log(rtfSpanish.format(threeDaysAgo, 'day'));
// "hace 3 días"

const rtfFrench = new Intl.RelativeTimeFormat('fr-FR');
console.log(rtfFrench.format(threeDaysAgo, 'day'));
// "il y a 3 jours"

const rtfGerman = new Intl.RelativeTimeFormat('de-DE');
console.log(rtfGerman.format(threeDaysAgo, 'day'));
// "vor 3 Tagen"

const rtfJapanese = new Intl.RelativeTimeFormat('ja-JP');
console.log(rtfJapanese.format(threeDaysAgo, 'day'));
// "3 日前"

const rtfArabic = new Intl.RelativeTimeFormat('ar-SA');
console.log(rtfArabic.format(threeDaysAgo, 'day'));
// "قبل 3 أيام"

각 언어는 원어민이 대화에서 사용할 법한 자연스러운 출력을 생성합니다. API는 다양한 문법 구조, 다양한 쓰기 시스템 및 다양한 텍스트 방향의 모든 복잡성을 처리합니다.

성능을 위한 포맷터 재사용

Intl.RelativeTimeFormat 인스턴스를 생성하는 것은 로케일 데이터를 로드하고 옵션을 처리하는 작업을 포함합니다. 여러 타임스탬프를 형식화할 때는 포맷터를 한 번 생성하고 재사용하세요.

const rtf = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });

const timestamps = [
  new Date(Date.now() - 5 * 60 * 1000),      // 5분 전
  new Date(Date.now() - 2 * 60 * 60 * 1000), // 2시간 전
  new Date(Date.now() - 24 * 60 * 60 * 1000) // 1일 전
];

timestamps.forEach(date => {
  const diffInMs = date - new Date();
  const diffInMinutes = Math.round(diffInMs / (60 * 1000));
  console.log(rtf.format(diffInMinutes, 'minute'));
});

이 접근 방식은 각 타임스탬프마다 새 포맷터를 생성하는 것보다 더 효율적입니다. 활동 피드나 댓글 스레드에서 수백 또는 수천 개의 타임스탬프를 형식화할 때 성능 차이가 크게 나타납니다.

인터페이스에서 상대적 시간 사용하기

사용자에게 타임스탬프를 표시하는 모든 곳에서 상대적 시간 형식을 사용할 수 있습니다. 여기에는 소셜 미디어 피드, 댓글 섹션, 활동 로그, 알림 시스템 및 무언가가 얼마나 오래 전에 발생했는지 보여주는 것이 사용자가 맥락을 이해하는 데 도움이 되는 모든 인터페이스가 포함됩니다.

const rtf = new Intl.RelativeTimeFormat(navigator.language, {
  numeric: 'auto'
});

function updateTimestamp(element, date) {
  const now = new Date();
  const diffInMs = date - now;
  const diffInMinutes = Math.round(diffInMs / (60 * 1000));

  element.textContent = rtf.format(diffInMinutes, 'minute');
}

const commentDate = new Date('2025-10-15T14:30:00');
const timestampElement = document.getElementById('comment-timestamp');

updateTimestamp(timestampElement, commentDate);

형식이 지정된 문자열은 다른 문자열 값과 같이 작동합니다. 텍스트 콘텐츠, 속성 또는 사용자에게 정보를 표시하는 다른 컨텍스트에 삽입할 수 있습니다.