@3/12/2023
목적
•
오늘 작성한 게시글은 16:41처럼 시간:분으로 표시하고, 오늘 이전 게시글은 년월일만 표시하고 싶음
DB에서 날짜를 문자열 형태로 받아오기 - X
DTO에 formattedRegDate 필드 추가
@AllArgsConstructor
@Getter @Setter
public class PostListDTO {
private Long postId;
private String title;
private String userName;
private LocalDateTime regDate;
private Integer view;
private String formattedRegDate;
}
Java
복사
•
필드만 추가하고 repository jpql에 손은 안 댔는데 오류가 남. 빈 값이라도 받아와야 하나 봄
public List<PostListDTO> findAll(int offset, int limit) {
String query = "select new dev.gyuray.forum.repository.post.PostListDTO(" +
"p.id, " +
"p.title, " +
"u.name, " +
"p.regDate, " +
"p.view, " +
"''" +
") " +
"from Post p " +
"join p.user u " +
"order by p.id desc";
return em.createQuery(query, PostListDTO.class)
.setFirstResult(offset)
.setMaxResults(limit)
.getResultList();
}
Java
복사
위처럼 빈 값을 필드로 받아오는 것으로 처리함
Service 계층에서 날짜 포매팅
•
페이징은 어느정도 뷰와 관련이 깊으니까 컨트롤러에서 처리했는데 날짜 포매팅은 서비스 계층에서 하는 것이 나을 것 같아 서비스 클래스에서 처리함
public List<PostListDTO> findAll(int pageNum, int pageSize) {
int firstIndex = (pageNum - 1) * pageSize;
List<PostListDTO> postListDTOs = postRepository.findAll(firstIndex, pageSize);
// 날짜 포매팅
for (PostListDTO postListDTO : postListDTOs) {
LocalDateTime regDate = postListDTO.getRegDate();
LocalDateTime now = LocalDateTime.now();
long diff = ChronoUnit.HOURS.between(regDate, now);
if (diff < 24) {
postListDTO.setFormattedRegDate(DateTimeFormatter.ofPattern("HH:mm").format(regDate));
} else {
postListDTO.setFormattedRegDate(DateTimeFormatter.ofPattern("yyyy-MM-dd").format(regDate));
}
}
return postListDTOs;
}
Java
복사
view 수정
<tr th:each="postListDTO : ${postListDTOs}" class="text-center">
<td th:text="${postListDTO.postId}">2</td>
<td th:text="${postListDTO.title}" class="text-start">공지사항 글제목</td>
<td th:text="${postListDTO.userName}">운영자</td>
<td th:text="${postListDTO.view}">1</td>
<td th:text="${postListDTO.formattedRegDate}">2023-03-01 12:34:56</td>
</tr>
Java
복사
regDate 대신 formattedRegDate 출력
테스트 및 결과
•
테스트 데이터를 위해 날짜를 아래처럼 랜덤으로 돌림
regDate = regDate.minusDays((int) (Math.random() * 5));
Java
복사
•
정상 출력 확인