[Spring] 날짜 데이터 포맷 바꾸기

류재성's avatar
Mar 13, 2024
[Spring] 날짜 데이터 포맷 바꾸기
 

1. View 확인

 
notion image
 
💡
데이터를 insert 할 때 Timestamp 를 사용하면 불필요한 시간이 포함된다. 이를 시-분 까지 표시되도록 변경한다.
 

2. 라이브러리 설치

날짜 포맷 바꿔주는 라이브러리

implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
 
💡
자열 조작, 숫자 조작, 날짜 및 시간 조작, 리플렉션(reflection) 및 클래스 조작, 예외 처리할 수 있다.

3. JUnit 테스

 
notion image
 
import org.apache.commons.lang3.time.DateFormatUtils; import org.junit.jupiter.api.Test; import java.sql.Timestamp; import java.util.Date; public class DataTest { @Test public void format_test(){ //timestamp 객체를 초기 Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis()); // Timestamp를 Date 객체로 변환 Date currentDate = new Date(currentTimestamp.getTime()); // 원하는 포맷으로 날짜를 변환 String formattedDate = DateFormatUtils.format(currentDate, "yyyy-MM-dd HH:mm"); // 포맷된 날짜 출력 System.out.println("Formatted Date: " + formattedDate); } }
notion image
 
 
 

4. Date Util 만들기

 
util/MyDateUtil
import org.apache.commons.lang3.time.DateFormatUtils; import java.sql.Timestamp; import java.util.Date; public class MyDateUtil { public static String timestampFormat(Timestamp time){ // Timestamp를 Date 객체로 변환 Date currentDate = new Date(time.getTime()); // 원하는 포맷으로 날짜를 변환 return DateFormatUtils.format(currentDate, "yyyy-MM-dd HH:mm"); } }
 

5. Entity 생성자 만들기

 
import jakarta.persistence.*; import lombok.Data; import shop.mtcoding.blog.util.MyDateUtil; import java.sql.Timestamp; @Entity @Data @Table(name = "board_tb") public class Board { @Id @GeneratedValue (strategy = GenerationType.IDENTITY) private Integer id; private String title; private String content; private String username; private Timestamp createdAt; //time 생성자를 호출하면 createdAt 의 포맷이 변경 public String getTime(){ return MyDateUtil.timestampFormat(createdAt); } }
 

6. View 출력

 
 
{{#boardList}} <div class="card mb-3"> <div class="card-body"> <h4 class="card-title">{{title}}</h4> <div class="mb-3">{{time}}</div> <a href="/board/{{id}}" class="btn btn-primary">상세보기</a> </div> </div> {{/boardList}}
 
💡
createdAt 대신 time 을 넣으면 getTime 생성자 호출된다.
 
notion image
Share article
RSSPowered by inblog