🧩 Problem Solving

[자바 코테 준비] Java8 LocalDate API

date
Jun 4, 2024
slug
coding-test-study-local-date
author
status
Public
category
🧩 Problem Solving
tags
summary
코테에 자주 나오는 날짜 더하기 및 빼기, 포맷팅 하는 방법 정리
type
Post
thumbnail

참고

 

java.time 패키지

  • Instant : 타임스탬프 ( 기계용 시간, EPOCH )
  • LocalDate : 시간이 없는 날짜 ( 타임존에 대한 참조가 없음 )
  • LocalTime : 날짜가 없는 시간 ( 타임존에 대한 참조가 없음 )
  • LocalDateTime : 날짜와 시간을 결합한 클래스
  • ZonedDateTime : UTC 에서 시간대 및 타임존에 대한 참조를 가진 시간과 날짜를 다루는 클래스
 

LocalDate 객체 생성

// 현재 날의 객체 얻기 LocalDate localDate = LocalDate.now(); // 2022-12-25 // 특정 일자의 날짜 가져오는 정적 메소드 LocalDate localDate = LocalDate.of( 2022, 12, 25 );
 

포맷팅을 통해 String → LocalDate 변환

import java.time.format.DateTimeFormatter; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd"); LocalDate today = LocalDate.parse(todayString, formatter);
 

LocalDate 객체에 year, month, week, day 더하기 빼기

  • plusYears(), minusYears()
  • plusMonths(), minusMonths()
  • plusWeeks(), minusWeeks()
  • plusDays(), minusDays()
public static void main(String args[]) { LocalDate todayLocalDate = LocalDate.now(); System.out.println("오늘 날짜: " + todayLocalDate); LocalDate fiveYearsAfterLocalDate = todayLocalDate.plusYears(5); LocalDate tenMonthsAfterLocalDate = todayLocalDate.plusMonths(10); LocalDate threeWeeksAfterLocalDate = todayLocalDate.plusWeeks(3); LocalDate twentyAfterLocalDate = todayLocalDate.plusDays(20); }
 

LocalDate 객체의 특정 부분 바꾸기

// 특정 날짜에서 특정 부분만 바꾸기 LocalDate localDate = LocalDate.now(); // 2022-12-12 localDate.withDayOfMonth( 31 ); // 2022-12-31 ( @param int dayOfMonth ) localDate.withMonth( 1 ); // 2022-01-12 ( @param int month ) localDate.withYear( 2023 ); // 2023-12-12 ( @param int year ) // 윤년 여부 localDate.isLeapYear(); // false
 

두 LocalDate 비교하기, 윤년 여부 확인

boolean isAfter(ChronoLocalDate other); boolean isBefore(ChronoLocalDate other); boolean isEqual(ChronoLocalDate other); boolean isLeapYear();
 
 
 
코딩테스트 연습을 하다 보면 종종 1~2번 문제에 날짜 연산 혹은 비교 문제가 나온다. 혹시 모르니 숙지해두도록 하자!