728x90
반응형
포스트 작성 날짜에서 일자만 뽑아내는 로직을 구현 중에,
@CreatedDate 로 생성한 생성일을 가져와서 어떻게 일자만 뽑아낼지 고민했다.
처음에는 String처럼 슬라이싱하여 일자만 뽑아낼 수 있지 않을까? 했었는데
구글링을 해보니, LocalDateTime 메소드에 이미 일자를 뽑아내는 메소드가 존재했다.
아래의 코드로 한번에 LocalDateTIme의 메소드들을 살펴보자.
LocalDateTime 메소드 예제
LocalDate today = Year.of(2017).atMonth(12).atDay(17);
System.out.println("Today : " + today);
System.out.println("Year : " + today.getYear());
System.out.println("Month : " + today.getMonth());
System.out.println("DayOfMonth : " + today.getDayOfMonth());
System.out.println("DayOfWeek : " + today.getDayOfWeek());
System.out.println("IsLeapYear : " + today.isLeapYear());
System.out.println("1 year after today: " + today.plusYears(1));
System.out.println("1 month after today: " + today.plusMonths(1));
System.out.println("1 day after today: " + today.plusDays(1));
LocalDate yesterday = today.minusDays(1);
System.out.println("Today is after yesterday? " + today.isAfter(yesterday));
System.out.println("Today is before yesterday? " + today.isBefore(yesterday));
LocalDateTime now = today.atTime(22, 46, 17, 348);
System.out.println("Now : " + now);
System.out.println("Hour: " + now.getHour());
System.out.println("Minute: " + now.getMinute());
System.out.println("Second: " + now.getSecond());
System.out.println("Nano: " + now.getNano());
Today : 2017-12-17
Year : 2017
Month : DECEMBER
DayOfMonth : 17
DayOfWeek : SUNDAY
IsLeapYear : false
1 year after today: 2018-12-17
1 month after today: 2018-01-17
1 day after today: 2017-12-18
Today is after yesterday? true
Today is before yesterday? false
Now : 2017-12-17T22:46:17.000000348
Hour: 22
Minute: 46
Second: 17
Nano: 348
예제 출처
[Java8 Time API] LocalDate, LocalTime, LocalDateTime 사용법
[Java8 Time API] LocalDate, LocalTime, LocalDateTime 사용법
Engineering Blog by Dale Seo
www.daleseo.com
728x90
반응형
'하루 작성 Today Project > Study' 카테고리의 다른 글
@CreatedDate Format 변경하기 (0) | 2022.11.02 |
---|---|
Try-with-resource를 통한 자원 해제 처리 (0) | 2022.11.02 |
DTO에 기본 생성자가 필요한 이유 (5) | 2022.11.02 |