JAVA/포스팅

java.time.LocalDate 클래스

짜집퍼박사(짜박) 2023. 11. 16. 18:13

java.time.LocalDate 클래스는 날짜 정보를 나타내기 위한 클래스로, 시간 정보를 포함하지 않습니다. 이 클래스는 특정 시간대의 날짜를 표현하며, 연, 월, 일 정보를 저장합니다. 

 

1. LocalDate 객체 생성

현재 날짜로 LocalDate 객체 생성

LocalDate currentDate = LocalDate.now();

특정 날짜로 LocalDate 객체 생성

LocalDate specificDate = LocalDate.of(2023, 11, 1);

 

2. LocalDate 객체에서 날짜 정보 가져오기

연도, 월, 일 정보 가져오기

int year = currentDate.getYear();
Month month = currentDate.getMonth();
int day = currentDate.getDayOfMonth();

요일 정보 가져오기

DayOfWeek dayOfWeek = currentDate.getDayOfWeek();

 

3. LocalDate 객체 연산

특정 날짜에 일 수 더하기 또는 빼기

LocalDate plusDays = currentDate.plusDays(5);
LocalDate minusMonths = currentDate.minusMonths(2);

특정 기간을 더하기 또는 빼기

Period periodToAdd = Period.ofMonths(3);
LocalDate plusPeriod = currentDate.plus(periodToAdd);
LocalDate minusWeeks = currentDate.minus(2, ChronoUnit.WEEKS);

 

4. LocalDate 객체 비교

다른 LocalDate 객체와의 비교

boolean isAfter = currentDate.isAfter(specificDate);
boolean isBefore = currentDate.isBefore(specificDate);
int comparison = currentDate.compareTo(specificDate);

 

5. LocalDate 객체의 출력

LocalDate 객체를 문자열로 변환

String dateAsString = currentDate.toString();

 

6. LocalDate 객체의 형식화

사용자 정의 형식으로 날짜를 문자열로 변환

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String formattedDate = currentDate.format(formatter);

 

주의사항

LocalDate 클래스는 불변(immutable)이며, 변경할 수 없는 객체입니다. 따라서 LocalDate 객체를 조작하는 메소드들은 새로운 LocalDate 객체를 반환합니다.
LocalDate 클래스는 java.time 패키지에서 제공하는 날짜와 시간 관련 클래스 중 하나로, 날짜 정보만 필요한 경우에 사용됩니다.
이러한 메소드들을 사용하여 LocalDate 객체를 효과적으로 활용할 수 있습니다.

 

With ChatGPT

'JAVA > 포스팅' 카테고리의 다른 글

java.time.LocalDateTime 클래스  (0) 2023.11.17
java.time.LocalTime 클래스  (0) 2023.11.17
java.time.Instant 클래스  (0) 2023.11.16
자바 java.time패키지의 주요 클래스  (0) 2023.11.16
자바 java.time패키지  (0) 2023.11.16