시간, 분 또는 초만 표시하려면 어떻게 해야 하나요?

Intl.DateTimeFormat에서 개별 시간 구성 요소를 표시하려면 hour, minute, second 옵션을 사용하세요

소개

시간 표시는 종종 특정 구성 요소만 보여줄 필요가 있습니다. 시계 위젯은 초 없이 시간과 분만 표시할 수 있습니다. 카운트다운 타이머는 초만 표시할 수 있습니다. 일정 관리 인터페이스는 약속 시간만 표시할 수 있습니다.

timeStyle: "short"와 같은 사전 설정 스타일을 사용하여 시간을 포맷팅하면 로케일에 의해 선택된 구성 요소 번들을 얻게 됩니다. 개별 부분을 제거하거나 특정 부분을 추가할 수 없습니다. 짧은 스타일에 초가 포함되어 있지만 시간과 분만 원한다면, 사전 설정은 필요에 맞지 않습니다.

자바스크립트의 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 형식 중에서 선택하기

numeric2-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" 프리셋이 초를 포함하지만 시간과 분만 필요한 경우, hourminute을 개별적으로 지정하세요.

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'  // 오류: 함께 사용할 수 없음
});

시간 스타일을 사용하거나 개별 구성 요소를 구성하는 방법 중 하나를 선택하세요. 둘 다 사용할 수는 없습니다.

시간 구성 요소 옵션을 날짜 구성 요소 옵션과 함께 사용할 수 있습니다. 이를 통해 특정 날짜 부분과 특정 시간 부분을 함께 표시할 수 있습니다.

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));
// 뉴욕 시간대로 변환된 시간 표시

사용자 로케일에 맞게 시간 형식 지정

브라우저의 언어 환경설정을 사용하여 각 사용자의 기대에 맞게 시간 형식을 지정합니다.

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));
// 출력은 사용자의 로케일에 따라 다름
// en-US의 경우: "2:05 PM"
// de-DE의 경우: "14:05"
// ja-JP의 경우: "14:05"

이렇게 하면 각 사용자의 로케일에 따라 적절한 시간 형식, 구분 기호 및 AM/PM 표시기가 자동으로 적용됩니다.

성능을 위해 포맷터 재사용

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));
});
// en-US의 경우 출력:
// "9:00 AM"
// "2:30 PM"
// "6:45 PM"

이 패턴은 시간 배열을 형식화하거나 사용자 인터페이스에 많은 타임스탬프를 표시할 때 성능을 향상시킵니다.

기억해야 할 사항

hour, minute, second 옵션을 사용하면 전체 시간 대신 특정 시간 구성 요소를 표시할 수 있습니다. 각 옵션은 numeric 또는 2-digit 값을 허용합니다. numeric 값은 앞에 오는 0을 생략하고, 2-digit 값은 앞에 오는 0을 포함합니다.

필요한 구성 요소를 정확히 표시하기 위해 여러 옵션을 조합할 수 있습니다. 포맷터는 로케일에 따라 구분 기호, 순서 및 서식을 자동으로 처리합니다.

시간 형식은 로케일에 따라 다릅니다. 일부 로케일은 AM/PM 표시기가 있는 12시간 형식을 사용하고, 다른 로케일은 표시기 없이 24시간 형식을 사용합니다. 모든 로케일에 대해 동일한 옵션을 지정하면 포맷터가 적절한 규칙을 적용합니다.

어떤 부분이 표시되는지 정확하게 제어해야 할 때는 개별 시간 구성 요소를 사용하세요. 표준 형식이 필요할 때는 시간 스타일을 사용하세요. 개별 구성 요소 옵션과 시간 스타일 옵션을 함께 사용할 수 없습니다.

사용자의 기대에 맞게 시간을 표시하려면 navigator.language에서 사용자의 로케일을 사용하여 시간을 형식화하세요. 여러 시간을 형식화할 때는 성능 향상을 위해 포맷터 인스턴스를 재사용하세요.