형식에 맞지 않는 날짜 형태 변환해서 렌더링하기
데이터 테이블에서 글 생성일시를 불러오면 이런 형태로 되어 있는 데이터들이 많다.
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>
'Programing > React' 카테고리의 다른 글
로그인 하지 않은 상태에서는 헤더가 렌더링 되지 않게 조건부 렌더링 설정하기 (0) | 2024.06.14 |
---|---|
TanStack Query 기본 사용법 (0) | 2024.06.14 |
002. 작업 환경 설정 (0) | 2024.05.30 |
001. 리액트의 특징과 Virtual DOM (0) | 2024.05.30 |
045. React - useMemo와 연산 최적화 (0) | 2024.05.30 |
댓글