-
손쉽게 일자별 start ~ end 검색 구현하기 : ZonedDateTime.truncatedTo(TemporalUnit unit)프로젝트 노트 2024. 3. 29. 10:43
오랜만에 검색 기능을 구현하다가 검색 일자별로 조금 더 쉽게 start와 end date를 구하고 싶다는 생각이 들어 조금 알아보다가 간편한 방법이 있어 공유하면 좋겠단 생각이 들었습니다.
아래 예시 코드를 보시죠!
...Something Codes... ZonedDateTime end = ZonedDateTime.now(); // 현재의 시간을 구합니다(Time zone) ZonedDateTime start = end.minusDays(day); // 특정 day의 값 만큼 이전 일자 데이터를 구합니다. // 여기서 day는 기본 7일로 설정하여 주간 검색 기능을 구현하였습니다. // 추가적으로 start의 경우 00시 00분부터 처리를 해달라는 요구사항이 있었습니다. // 이를 간편하게 처리하기 위해 ZonedDateTime의 trunatedTo메소드를 활용하였습니다. start = start.truncatedTo(ChronoUnits.DAYS); log.info("start = {}, end = {}", start, end); // 제대로 데이터가 잘렸는지 log를 찍어보았습니다. ...Something Codes...
간편하게 구현해본 주간 검색 기능 구현 코드입니다.
ZonedDateTime 클래스의 truncatedTo 메소드를 활용하면 쉽게 일자별로 00시 00분을 맞출 수 있습니다.
물론 일자까지 잘라서 사용을 해도 되겠지만..쉬운 방법이 있는데 굳이 그런 방법을 사용할 필요가 있을까라는 생각으로 구현해봤습니다.
이렇게 사용하면 다음과 같이 로그가 찍힙니다.
start = 2024-03-22T00:00+09:00[Asia/Seoul], end = 2024-03-29T10:39:14.572+09:00[Asia/Seoul]
일자까지 두고 뒷부분이 초기화 된 모습을 볼 수 있습니다.
이를 통해 손쉽게 Period Search Condition을 설정할 수 있습니다.
참고로 코드에서 사용한 ChronoUnit의 경우 시간을 나타내는 열거형 타입으로 DAYS, HOURS, MINUTES, SECONDS, MILLIS, MICROS, NANOS 등을 정의하고 있습니다.
이상입니다!
'프로젝트 노트' 카테고리의 다른 글
초간단 Docker에서 Tomcat 설치하기 (0) 2024.05.13 Ubuntu 20.04 LTS에 Docker 설치하기 (0) 2024.05.13 Ubuntu (우분투) 환경에서 OpenSearch Dashboard 설치 및 외부 접속 설정 (0) 2023.12.12 Ubuntu (우분투) 에 OpenSearch (오픈서치) 설치하기 (0) 2023.12.12 OpenSearch + Spring Boot + Java 연동 예제 (HTTPS 및 Apache HttpClient 5 활용하기!) (1) 2023.12.06