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"를 구분합니다. 아랍어는 개수에 따라 6가지 다른 복수형을 가집니다. 일본어는 수량에 관계없이 동일한 형태를 사용합니다. 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와 같은 복수형을 모두 허용합니다. 둘 다 동일한 출력을 생성합니다. 분기 단위는 회계 기간을 다루는 비즈니스 애플리케이션에 유용합니다.
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"
numeric를 auto로 설정하면 특정 값에 대해 더 자연스러운 표현이 생성됩니다.
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일 전" 대신 "어제"를 보게 되며, 이는 더 자연스럽게 읽힙니다. 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'));
// Output varies by user's locale
// For en-US: "yesterday"
// For es-ES: "ayer"
// For fr-FR: "hier"
// For 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 minutes ago
new Date(Date.now() - 2 * 60 * 60 * 1000), // 2 hours ago
new Date(Date.now() - 24 * 60 * 60 * 1000) // 1 day ago
];
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);
형식화된 문자열은 다른 문자열 값과 동일하게 작동합니다. 텍스트 콘텐츠, 속성 또는 사용자에게 정보를 표시하는 다른 컨텍스트에 삽입할 수 있습니다.