시간, 분 또는 초만 표시하려면 어떻게 해야 하나요?
Intl.DateTimeFormat에서 hour, minute, second 옵션을 사용하여 개별 시간 구성 요소 표시하기
소개
시간 표시는 종종 특정 구성 요소만 표시해야 합니다. 시계 위젯은 초 없이 시와 분만 표시할 수 있습니다. 카운트다운 타이머는 초만 표시할 수 있습니다. 일정 관리 인터페이스는 약속 시간만 표시할 수 있습니다.
timeStyle: "short"와 같은 사전 설정 스타일을 사용하여 시간을 형식화하면 로케일에서 선택한 구성 요소 번들을 얻게 됩니다. 개별 부분을 제거하거나 특정 부분을 추가할 수 없습니다. 짧은 스타일에 초가 포함되어 있지만 시와 분만 원하는 경우 사전 설정이 요구 사항에 맞지 않습니다.
JavaScript의 Intl.DateTimeFormat는 각 시간 구성 요소에 대한 개별 옵션을 제공합니다. 포함할 부분과 각 부분의 형식을 정확하게 지정할 수 있습니다. 이 레슨에서는 시, 분, 초를 개별적으로 또는 특정 조합으로 표시하는 방법을 설명합니다.
시간 구성 요소 이해하기
시간에는 독립적으로 포맷할 수 있는 세 가지 주요 구성 요소가 있습니다.
hour는 하루 중 몇 시인지 표시합니다. minute는 시간 중 몇 분인지 표시합니다. second는 분 중 몇 초인지 표시합니다.
각 구성 요소는 표시 방법을 제어하는 포맷 값을 허용합니다. 옵션 객체에 필요한 구성 요소만 포함하면 됩니다.
시간만 포맷하기
hour 옵션은 시간 구성 요소를 표시합니다. 두 가지 값을 허용합니다.
const time = new Date('2025-03-15T14:05:00');
const numeric = new Intl.DateTimeFormat('en-US', {
hour: 'numeric'
});
console.log(numeric.format(time)); // "2 PM"
const twoDigit = new Intl.DateTimeFormat('en-US', {
hour: '2-digit'
});
console.log(twoDigit.format(time)); // "02 PM"
numeric 값은 선행 0 없이 시간을 표시합니다. 2-digit 값은 필요한 경우 선행 0과 함께 시간을 표시합니다.
미국 영어의 경우 포매터는 AM/PM 표시가 있는 12시간 형식을 사용합니다. 다른 로케일은 다른 규칙을 사용하며, 이는 이 레슨의 뒷부분에서 다룹니다.
분만 형식 지정
minute 옵션은 분 구성 요소를 표시합니다. 두 가지 값을 허용합니다.
const time = new Date('2025-03-15T14:05:00');
const numeric = new Intl.DateTimeFormat('en-US', {
minute: 'numeric'
});
console.log(numeric.format(time)); // "5"
const twoDigit = new Intl.DateTimeFormat('en-US', {
minute: '2-digit'
});
console.log(twoDigit.format(time)); // "05"
numeric 값은 선행 0 없이 분을 표시합니다. 2-digit 값은 선행 0과 함께 분을 표시합니다.
분만 표시하는 것은 시간이나 초만 표시하는 것보다 덜 일반적입니다. 대부분의 시간 표시는 분을 시간과 결합합니다.
초만 형식 지정
second 옵션은 초 구성 요소를 표시합니다. 두 가지 값을 허용합니다.
const time = new Date('2025-03-15T14:05:08');
const numeric = new Intl.DateTimeFormat('en-US', {
second: 'numeric'
});
console.log(numeric.format(time)); // "8"
const twoDigit = new Intl.DateTimeFormat('en-US', {
second: '2-digit'
});
console.log(twoDigit.format(time)); // "08"
numeric 값은 선행 0 없이 초를 표시합니다. 2-digit 값은 선행 0과 함께 초를 표시합니다.
이는 카운터에서 경과 초를 표시하거나 타임스탬프의 초 부분을 표시하는 데 적합합니다.
시간과 분 결합
대부분의 시간 표시는 시간과 분을 모두 표시합니다. 단일 포매터에서 이러한 옵션을 결합할 수 있습니다.
const time = new Date('2025-03-15T14:05:00');
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit'
});
console.log(formatter.format(time)); // "2:05 PM"
포매터는 로케일에 따라 적절한 구분 기호와 형식을 자동으로 추가합니다. 미국 영어의 경우 콜론 구분 기호와 AM/PM 표시기가 생성됩니다.
구분 기호나 순서를 지정할 필요가 없습니다. 로케일이 이러한 세부 사항을 결정합니다.
시간, 분, 초 결합
완전한 시간 정밀도가 필요한 경우 세 가지 시간 구성 요소를 모두 포함할 수 있습니다.
const time = new Date('2025-03-15T14:05:08');
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
});
console.log(formatter.format(time)); // "2:05:08 PM"
이는 시간, 분, 초가 포함된 전체 시간을 생성합니다. 포매터는 모든 구분 기호와 형식 규칙을 처리합니다.
분 없이 시간과 초 결합
분을 포함하지 않고 시간과 초를 결합할 수도 있지만 이는 드뭅니다.
const time = new Date('2025-03-15T14:05:08');
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
second: '2-digit'
});
console.log(formatter.format(time)); // "2:08 PM"
포매터는 비정상적인 구성 요소 조합에 대해서도 합리적인 출력을 생성합니다.
numeric과 2-digit 형식 중 선택
numeric와 2-digit의 차이는 한 자리 값에서 가장 중요합니다.
const earlyTime = new Date('2025-03-15T08:05:03');
const lateTime = new Date('2025-03-15T14:35:48');
const numericFormatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
const digitFormatter = new Intl.DateTimeFormat('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
console.log('Numeric:');
console.log(numericFormatter.format(earlyTime)); // "8:5:3 AM"
console.log(numericFormatter.format(lateTime)); // "2:35:48 PM"
console.log('2-digit:');
console.log(digitFormatter.format(earlyTime)); // "08:05:03 AM"
console.log(digitFormatter.format(lateTime)); // "02:35:48 PM"
numeric 형식은 앞에 0을 생략하여 "8:5:3 AM"과 같은 값을 생성합니다. 2-digit 형식은 앞에 0을 포함하여 "08:05:03 AM"을 생성합니다.
대부분의 경우 분과 초에는 2-digit를 사용하세요. 이렇게 하면 표, 목록 또는 디지털 시계 표시에서 일관된 너비와 정렬이 보장됩니다. 앞에 0이 없으면 "8:5 AM"과 같은 시간이 불규칙하게 보입니다.
시간의 경우 선택은 디자인에 따라 다릅니다. 디지털 시계는 일관성을 위해 2-digit를 자주 사용합니다. 텍스트 표시는 보다 자연스러운 모양을 위해 numeric를 자주 사용합니다.
로케일에 따른 시간 형식 차이
로케일마다 시간 표시에 다른 규칙을 사용합니다. 미국 영어는 AM/PM 표시가 있는 12시간 형식을 사용합니다. 다른 많은 로케일은 24시간 형식을 사용합니다.
const time = new Date('2025-03-15T14:05:00');
const en = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit'
});
console.log(en.format(time)); // "2:05 PM"
const de = new Intl.DateTimeFormat('de-DE', {
hour: 'numeric',
minute: '2-digit'
});
console.log(de.format(time)); // "14:05"
const fr = new Intl.DateTimeFormat('fr-FR', {
hour: 'numeric',
minute: '2-digit'
});
console.log(fr.format(time)); // "14:05"
const ja = new Intl.DateTimeFormat('ja-JP', {
hour: 'numeric',
minute: '2-digit'
});
console.log(ja.format(time)); // "14:05"
미국 영어는 24시간 값을 12시간 형식으로 변환하고 "PM"을 추가합니다. 독일어, 프랑스어, 일본어는 모두 AM/PM 표시 없이 24시간 형식을 사용합니다.
모든 로케일에 대해 동일한 옵션을 지정합니다. 포매터는 로케일 규칙에 따라 적절한 시간 형식을 자동으로 적용합니다.
로케일에 따른 구분 기호 차이
시간 구성 요소 간의 구분 기호도 로케일에 따라 다릅니다.
const time = new Date('2025-03-15T14:05:08');
const options = {
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
};
const en = new Intl.DateTimeFormat('en-US', options);
console.log(en.format(time)); // "2:05:08 PM"
const fi = new Intl.DateTimeFormat('fi-FI', options);
console.log(fi.format(time)); // "14.05.08"
미국 영어는 구성 요소 사이에 콜론을 사용합니다. 핀란드어는 마침표를 사용합니다. 구분 기호를 지정하지 않습니다. 포매터가 각 로케일에 적합한 구분 기호를 선택합니다.
개별 시간 구성 요소를 사용해야 하는 경우
사전 설정된 시간 스타일이 요구 사항과 맞지 않을 때 개별 시간 구성 요소를 사용하세요.
시간과 분은 필요하지만 초는 필요하지 않고 대상 로케일에 대해 timeStyle: "short" 프리셋에 초가 포함된 경우 hour와 minute를 개별적으로 지정하세요.
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit'
});
간소화된 시계나 일정에 시간만 표시해야 하는 경우 hour 옵션만 사용하세요.
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric'
});
타이머나 카운터에서 경과된 초를 표시해야 하는 경우 second 옵션만 사용하세요.
const formatter = new Intl.DateTimeFormat('en-US', {
second: '2-digit'
});
시간 스타일을 사용해야 하는 경우
완전한 시간 표시가 필요하고 프리셋 스타일이 로케일에 적합한 경우 대신 timeStyle를 사용하세요. 프리셋 스타일은 더 간단하며 로케일 전체에서 일관된 형식을 보장합니다.
const formatter = new Intl.DateTimeFormat('en-US', {
timeStyle: 'short'
});
이렇게 하면 개별 옵션을 지정하지 않고도 적절한 구성 요소와 형식이 자동으로 선택됩니다.
어떤 부분이 표시될지 정확하게 제어해야 하는 경우 개별 시간 구성 요소를 사용하세요. 사용자 지정 없이 표준적이고 로케일에 적합한 형식을 원하는 경우 시간 스타일을 사용하세요.
특정 시간 부분의 일반적인 사용 사례
정확한 분이 덜 중요하거나 별도로 처리되는 예약 일정 인터페이스에서는 시간만 표시합니다.
const time = new Date('2025-03-15T14:00:00');
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric'
});
console.log(`Meeting at ${formatter.format(time)}`);
// "Meeting at 2 PM"
초 단위 정밀도가 불필요한 대부분의 시계 위젯 및 시간 표시에는 시간과 분을 표시합니다.
const time = new Date('2025-03-15T14:05:00');
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit'
});
console.log(formatter.format(time));
// "2:05 PM"
경과 초를 표시하는 카운트다운 타이머에는 초만 표시합니다.
const time = new Date('2025-03-15T00:00:45');
const formatter = new Intl.DateTimeFormat('en-US', {
second: '2-digit'
});
console.log(`${formatter.format(time)} seconds remaining`);
// "45 seconds remaining"
로그나 감사 추적의 정밀한 타임스탬프에는 시간, 분, 초를 표시합니다.
const time = new Date('2025-03-15T14:05:08');
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
second: '2-digit'
});
console.log(`Event logged at ${formatter.format(time)}`);
// "Event logged at 2:05:08 PM"
개별 구성 요소 사용 시 제한 사항
hour, minute 또는 second와 같은 개별 시간 구성 요소 옵션을 timeStyle 옵션과 결합할 수 없습니다. timeStyle 프리셋은 이미 어떤 구성 요소가 나타나고 어떻게 형식화되는지 결정합니다.
다음은 작동하지 않습니다:
const formatter = new Intl.DateTimeFormat('en-US', {
timeStyle: 'short',
second: '2-digit' // Error: cannot combine
});
시간 스타일을 사용하거나 개별 구성 요소를 구성하는 것 중 하나를 선택하세요. 둘 다 사용할 수 없습니다.
시간 구성 요소 옵션을 날짜 구성 요소 옵션과 결합할 수 있습니다. 이를 통해 특정 날짜 부분과 특정 시간 부분을 함께 표시할 수 있습니다.
const formatter = new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
});
const datetime = new Date('2025-03-15T14:05:00');
console.log(formatter.format(datetime));
// "Mar 15, 2:05 PM"
timeZone, calendar 또는 numberingSystem와 같은 옵션과 시간 구성 요소를 결합할 수도 있습니다.
const formatter = new Intl.DateTimeFormat('en-US', {
hour: 'numeric',
minute: '2-digit',
timeZone: 'America/New_York'
});
const time = new Date('2025-03-15T14:05:00Z');
console.log(formatter.format(time));
// Displays time converted to New York timezone
사용자의 로케일에 맞게 시간 형식 지정
브라우저의 언어 기본 설정을 사용하여 각 사용자의 기대에 맞게 시간을 형식화합니다.
const formatter = new Intl.DateTimeFormat(navigator.language, {
hour: 'numeric',
minute: '2-digit'
});
const time = new Date('2025-03-15T14:05:00');
console.log(formatter.format(time));
// Output varies by user's locale
// For en-US: "2:05 PM"
// For de-DE: "14:05"
// For ja-JP: "14:05"
이렇게 하면 각 사용자의 로케일에 따라 적절한 시간 형식, 구분 기호 및 오전/오후 표시가 자동으로 적용됩니다.
성능을 위해 포맷터 재사용
Intl.DateTimeFormat 인스턴스를 생성하려면 로케일 데이터와 옵션을 처리해야 합니다. 동일한 설정으로 여러 번 형식을 지정할 때는 포매터를 한 번 생성하고 재사용하세요.
const formatter = new Intl.DateTimeFormat(navigator.language, {
hour: 'numeric',
minute: '2-digit'
});
const times = [
new Date('2025-03-15T09:00:00'),
new Date('2025-03-15T14:30:00'),
new Date('2025-03-15T18:45:00')
];
times.forEach(time => {
console.log(formatter.format(time));
});
// Output for en-US:
// "9:00 AM"
// "2:30 PM"
// "6:45 PM"
이 패턴은 시간 배열을 형식화하거나 사용자 인터페이스에 많은 타임스탬프를 표시할 때 성능을 향상시킵니다.
기억해야 할 사항
hour, minute 및 second 옵션을 사용하면 전체 시간 대신 특정 시간 구성 요소를 표시할 수 있습니다. 각 옵션은 numeric 또는 2-digit 값을 허용합니다. numeric 값은 앞에 0을 생략합니다. 2-digit 값은 앞에 0을 포함합니다.
여러 옵션을 결합하여 필요한 구성 요소만 정확하게 표시할 수 있습니다. 포맷터는 로케일에 따라 구분 기호, 순서 및 형식을 자동으로 처리합니다.
시간 형식은 로케일에 따라 다릅니다. 일부 로케일은 오전/오후 표시와 함께 12시간 형식을 사용합니다. 다른 로케일은 표시 없이 24시간 형식을 사용합니다. 모든 로케일에 대해 동일한 옵션을 지정하면 포맷터가 적절한 규칙을 적용합니다.
어떤 부분을 표시할지 정확하게 제어해야 할 때는 개별 시간 구성 요소를 사용하세요. 표준 형식을 원할 때는 시간 스타일을 사용하세요. 개별 구성 요소 옵션과 시간 스타일 옵션을 함께 사용할 수 없습니다.
navigator.language에서 사용자의 로케일을 사용하여 시간을 형식화하면 각 사용자의 기대에 맞게 시간을 표시할 수 있습니다. 더 나은 성능을 위해 여러 번 형식화할 때는 포매터 인스턴스를 재사용하세요.