LocalDateTime 간의 시간 차이 계산

송형근·2024년 8월 29일
0

TIL

목록 보기
25/43
post-thumbnail

프로젝트에서 주문 취소시 주문 생성 후 5분 초과시 취소할 수 없게 구현 해야하는 요건이 존재

LocalTime

  • LocalDateTime과는 달리 시간만 존재하는 클래스

Duration

  • 시간의 길이를 나타내는 클래스

구현

	Order order = orderRepository.findOneByOrderIdAndDeletedAtIsNull(orderId).orElseThrow(()->{
                log.error("주문 정보를 찾을 수 없음");
                return new ResponseStatusException(HttpStatus.NOT_FOUND, "주문 정보를 찾을 수 없음");
           }
    );
	LocalDateTime now = LocalDateTime.now()
	LocalTime currentTime = now.toLocalTime();
    LocalTime createdTime = order.getCreatedAt().toLocalTime();
    long diffMin = Duration.between(createdTime, currentTime).isNegative() ?
                Duration.between(createdTime, now).plusDays(1).toMinutes() : Duration.between(createdTime, currentTime).toMinutes();
    if(diffMin >= 5 || !now.toLocalDate().equals(order.getCreatedAt().toLocalDate())){
        log.error("주문 후 5분 초과로 취소 불가");
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "주문 후 5분 초과로 취소 불가");
    }
  • 시간간의 차이를 계산하기 위해 우선 LocalDateTime의 toLocalTime 메서드를 이용해 변환해줌
  • Duration의 between 메서드를 통해 현재 시간과 DB에 저장되어있던 생성시간의 차이를 계산하고 toMinues 메서드를 통해 분으로 변환
  • 차이가 5분을 넘어가거나 날짜가 다르면 Exception 발생시킴
profile
기록을 남겨보자

0개의 댓글