게시일: 2025년 3월 20일
웹페이지에 표시되는 일반적인 정보는 특정 이벤트까지의 시간 또는 이벤트가 발생한 후 경과된 시간을 나타내는 텍스트입니다. 이는 일반적으로 시간 경과 시간을 시간, 분, 초 또는 기타 유용한 시간 단위로 전달하는 문자열로 표현됩니다.
Intl.DurationFormat
는 JavaScript를 추가하지 않고도 브라우저에서 이 작업을 실행하면서 언어 현지화 요구사항을 고려하는 유용한 기능입니다. 2025년 3월부터는 기준점 새로 사용 가능으로 변경되었습니다.
Intl.DurationFormat
작동 방식
Intl.DurationFormat
는 인스턴스화 시 시간 지속 시간을 나타내는 문자열을 반환하는 클래스입니다. 문자열을 생성할 시간 단위에 해당하는 키와 값이 포함된 객체를 지정하여 작동합니다.
// Specify the duration:
const duration = {
years: 1,
hours: 20,
minutes: 15,
seconds: 35
};
// Output: '1 yr, 20 hr, 15 min, 35 sec'
new Intl.DurationFormat('en').format(duration);
긴 형식의 문자열을 반환하려면 생성자의 두 번째 인수에서 style
옵션에 'long'
값을 전달합니다.
const duration = {
years: 1,
hours: 20,
minutes: 15,
seconds: 35
};
// Output: '1 year, 20 hours, 15 minutes, 35 seconds'
new Intl.DurationFormat('en', { style: 'long' }).format(duration);
지금까지 이러한 예에서는 영어로 문자열을 생성합니다. 이 기능은 국제화 기능이므로 유효한 언어를 전달하고 필요한 지원 언어로 형식이 지정된 문자열을 가져올 수 있다는 점이 실제로 유용합니다.
const duration = {
years: 1,
hours: 20,
minutes: 15,
seconds: 35
};
// Output: '1 Jahr, 20 Stunden, 15 Minuten und 35 Sekunden'
new Intl.DurationFormat('de', { style: 'long' }).format(duration);
// Output: '1 año, 20 horas, 15 minutos y 35 segundos'
new Intl.DurationFormat('es', { style: 'long' }).format(duration);
// Output: '1年20小时15分钟35秒钟'
new Intl.DurationFormat('zh', { style: 'long' }).format(duration);
// Output: '1 år, 20 timer, 15 minutter og 35 sekunder'
new Intl.DurationFormat('no', { style: 'long' }).format(duration);
// Output: 'mwaka 1, saa 20, dakika 15 na sekunde 35'
new Intl.DurationFormat('sw', { style: 'long' }).format(duration);
다음 예는 이 새로운 기능으로 할 수 있는 작업을 간략히 보여줍니다. Intl.DurationFormat
의 기능에 대해 자세히 알아보려면 MDN의 Intl.DurationFormat
문서를 참고하세요.