본문 바로가기

포매팅 함수 - 데이터를 원하는 형식으로 변환하기

codeConnection 2024. 6. 17.

상황

원본 데이터 날짜 형태가 2022-08-31T12:49:00.000Z

이러한 형태로 저장되어 있어 데이터를 fetch 해 와서 렌더링 시킬 때 저대로 렌더링 됨.

이것을 2024년 6월 17일 과 같은 형태로 변환하고자 함.

 

이 외에도 금액이 100000과 같이 나오는 것을 세 자리수 마다 콤마를 찍는 포매팅 함수 등도 여러 가지 알아보고자 함.

포매팅 함수 작성

YYYY년 MM월 DD일

const formatDate = (dateString) => {
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  const date = new Date(dateString);
  return date.toLocaleDateString('ko-KR', options).replace(/ /g, ' ');
};

세 자릿수 콤마

const formatNumber = (number) => {
  return number.toLocaleString('ko-KR');
};

데이터 바인딩하는 부분에서 감싸기

// 기존
<Card.Subtitle className="mb-2 text-muted">{item.날짜}</Card.Subtitle>

// 감싼 후
<Card.Subtitle className="mb-2 text-muted">{formatDate(item.날짜)}</Card.Subtitle>

번외 : 유틸 함수로 만들어서 다른 컴포넌트에서 재사용 하기

포매팅 함수를 다른 컴포넌트에서 계속 사용해야 하는 경우 별도의 유틸 함수로 작성해서 필요한 컴포넌트에서 호출해서 재사용하는 방법이 있다.

utils.js 파일 생성

// src/utils.js
export const formatDate = (dateString) => {
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  const date = new Date(dateString);
  return date.toLocaleDateString('ko-KR', options).replace(/ /g, ' ');
};

export const formatAmount = (number) => {
  return number.toLocaleString('ko-KR');
};

필요한 컴포넌트에서 Import

// SponsorList.jsx

import { formatDate, formatAmount } from './utils';

...



  return (
    <CenteredContainer>
 
                <Card.Title>{formatAmount(item.절대값)} 원</Card.Title>
                
                <Card.Subtitle className="mb-2 text-muted">{formatDate(item.날짜)}</Card.Subtitle>

    </CenteredContainer>
  );

댓글