API로 날짜 형식을 '20241011'로 받았다. 이를 '2024년 10월 11일' 형태로 출력해보자!
function formatDateKorean(dateStr: string): string {
const year = dateStr.slice(0, 4);
const month = dateStr.slice(4, 6);
const day = dateStr.slice(6, 8);
return `${year}년 ${parseInt(month)}월 ${parseInt(day)}일`;
}
// 사용 예시
const formattedDate = formatDateKorean('20241011');
console.log(formattedDate); // 출력: 2024년 10월 11일
- slice 메서드를 사용하여 입력 문자열에서 년, 월, 일을 추출
- 템플릿 리터럴을 사용하여 원하는 형식의 문자열을 생성
- parseInt를 사용하여 월과 일의 앞에 오는 0을 제거
'Typescript' 카테고리의 다른 글
[Typescript] 문자열 내 괄호의 개수 계산하기 (1) | 2024.12.26 |
---|