본문 바로가기
프로그래밍/TIL

[TIL] LocalDateTime to String, String to LocalDateTime

by 코딩중독 2024. 1. 31.

목차

     

    Java Spring 프로젝트 실습을 진행하다 보면 LocalDateTime을 사용할 일이 잦다.

    사용자의 가입일자, 게시글의 등록일자, 변경일자 등 정확한 날짜와 시간을 데이터베이스에 저장하기 위해서 쓰인다.

    이번 토이프로젝트에서도 여행정보를 저장할 때 여정정보를 저장할 때 날짜와 시간 부분에 많이 사용했다.

    팀원들끼리 소통을 하면서 진행했지만 역시 아무 일도 없이 지나갈 수는 없는 법.

    Entity와 DTO를 만드는 과정에서 Entity에서는 LocalDateTime으로 만들고 DTO에서는 String으로 만드는 바람에 여러 가지 해결방법이 있겠지만 1차적으로 데이터타입을 수정하지 않고 DTO에서 Entity로 변환해 주는 과정에서 String을 LocalDateTime으로 변환하는 작업을 수행했다.

     

    [DTO, Entity]

    public class TripDTO {
        private String startDate;
        private String endDate;
    }
    
    public class Trip {
        private LocalDateTime startDate;
        private LocalDateTime endDate;
    }

     

    [TripConverter]

        public Trip toEntity(TripDTO dto){
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
            String startDate = dto.getStartDate();
            String endDate = dto.getEndDate();
    
            return new Trip(dto.getId(), dto.getUserId(), dto.getName(),
                    LocalDateTime.parse(startDate, formatter),
                    LocalDateTime.parse(endDate, formatter),
                    dto.getStatus());
        }

     

     

    [주의할 점]

    이전 포스팅에도 여러 번 내용을 담았고 이전 프로젝트에서도 겪었던 부분이지만, LocalDateTime에서 시:분:초를 필수값으로 요구한다.

    String strTime = "2024-01-01 11:11:11";
    
    // 포맷 지정
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // String to LocalDateTime
    LocalDateTime dateTime = LocalDateTime.parse(strTime, formatter);
    
    // LocalDateTime to String
    String newTime = dateTime.format(formatter);

     

    위 Converter 내용처럼 문자열에 시:분:초 값이 누락된다면 파싱에러가 발생하게 된다.

    java.time.format.DateTimeParseException: Text '2024-01-01' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2024-01-01 of type java.time.format.Parsed
    
    java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2024-01-01 of type java.time.format.Parsed

     

     

    내일 팀원들과 내용을 공유하고 Converter를 수정해야 한다.