본문 바로가기

형식에 맞지 않는 날짜 형태 변환해서 렌더링하기

codeConnection 2024. 6. 4.

데이터 테이블에서 글 생성일시를 불러오면 이런 형태로 되어 있는 데이터들이 많다.

2024-06-04T08:06:49.657004+00:00

작성일을 렌더링 할 때 저대로 보여주면 곤란하므로, 우리가 원하는 방식으로 아래처럼 포매팅을 해주면 된다.

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}${month}${day}${hours}${minutes}${seconds}초`;
  };

그리고 렌더링 하는 부분에서 포매팅 함수로 감싸서 바인딩 해주면 된다.

// 함수로 감싸기 전
<p className="post__date">{item.created_at}</p>

// 함수로 감싼 후
<p className="post__date">{formatDate(item.created_at)}</p>

댓글