Java API (3) - java.time 패키지

2025. 2. 25. 11:07Java/Java 문법

java.time 패키지 

  • java.time 패키지는 Java 8에서 추가된 현대적인 날짜/시간 API
  • 기존에 Date, Calendar 가 가지고 있는 단점들을 해소하기 위해서 탄생되었다.
  • Time 패키지의 가장 큰 장점은 Date와 Calendar와 다르게 불변하여 멀티스레드 환경에서도 안전하다.
  • String 처럼 날짜와 시간을 변경을 하면 기존의 객체가 변경되는 것이 아닌 새로운 객체가 반환된다. 
  • 하위 패키지
    패키지 설명
    java.time 날짜와 시간 관련 클래스들을 제공한다
    java.time.chrono ISO-8601 에 정의된 외에 달력 시스템을 위한 클래스들을 제공한다
    java.time.format 날짜와 시간 파싱과 형식화 관련 클래스들을 제공한다
    java.time.temporal 날짜와 시간의 필드와 단위 관련 클래스들을 제공한다
    java.time.zone 시간대 관련된 클래스들을 제공한다
  • 핵심 클래스 
    클래스명 설명
    LocalTime 시간 관련 작업할 때 사용하는 클래스. LocalTime 객체는 두 개의 정적 메소드를 통해 반환 받을 수 있다.
    LocalDate 날짜 관련 작업할 때 사용하는 클래스. LocalDate 객체도 두 개의 정적 메소드로 반환 받는다.
    LocalDateTime 시간과 날짜를 함께 작업해야할 때 사용하는 클래스
    ZonedDateTime 시간대(Time Zone) 을 활용한 작업해야할 때 사용하는 클래스

 

1. 날짜와 시간 객체 생성, 필드값 가져오기 : now(), of(), getXX()

1) LocalDate [년-월-일]

//LocalDate
// now() : 자신의 PC의 현재 날짜 기준으로 LocalDate 객체 반환
// of() : 매개변수로 받은 날짜 기준으로 LocalDate 객체 반환
LocalDate localDate = LocalDate.now(); //2021-09-16 (현재 날짜)
LocalDate myDate = LocalDate.of(2021, 1, 1); //2021-01-01 (년, 월, 일)
    
//값 가져오기
System.out.println("localDate = " 	+ localDate); //2021-09-16
System.out.println("년 : " 		+ localDate.getYear()); //2021
System.out.println("월(영어) : " 	+ localDate.getMonth()); //SEPTEMBER
System.out.println("월 : " 		+ localDate.getMonthValue()); //9
System.out.println("월 중 몇 번째 일 : " + localDate.getDayOfMonth()); //16
System.out.println("일년 중 몇 번째 일 : " + localDate.getDayOfYear()); //259
System.out.println("요일(영어) : " 	+ localDate.getDayOfWeek()); //THURSDAY
System.out.println("윤년 여부 : " 	+ localDate.isLeapYear()); //false

 

2) LocalTime [시간:분:초.나노초]

//LocalTime
// now() : 자신의 PC의 현재 시간 기준으로 LocalTime 객체 반환
// of() : 매개변수로 받은 시간 기준으로 LocalTime 객체 반환
LocalTime myTime = LocalTime.of(12, 10, 30); //12:10:30 (시간, 분, 초, 나노초)
LocalTime localTime = LocalTime.now(); //17:30:26.293112 (현재 시간)

System.out.println("localTime = " + localTime); //17:30:26.293112
System.out.println("시간 : " 	+ localTime.getHour()); //17
System.out.println("분 : " 	+ localTime.getMinute()); //30
System.out.println("초 : " 	+ localTime.getSecond()); //26
System.out.println("나노초 : " 	+ localTime.getNano()); //293112

 

3) LocalDateTime [년-월-일T시간:분:초.나노초]

//LocalDateTime
// now() : 자신의 PC의 현재 시간과 날짜 기준으로 LocalDate 객체 반환
// of() : 매개변수로 받은 시간과 날짜 기준으로 LocalDate 객체 반환
    
// 2021-01-01T12:10:30 (년, 월, 일, 시간, 분, 초, 나노초) 
LocalDateTime myDateTime = LocalDateTime.of(2021,1,1,12,10,30);

//2021-09-16T17:51:59.951920
LocalDateTime localDateTime = LocalDateTime.now();

 

4) ZonedDateTime

//ZonedDateTime
// now() : ZoneId를 매개변수로 넘겨주면 ZonedDateTime 객체를 반환
// of() : 매개변수로 java.util.TimeZone 의 getAvailableIDs() 메소드가 반환하는 값을 넣어 ZoneId 반환 받을 수 있다
ZonedDateTime zonedDateTimeNow = ZonedDateTime.now();
ZonedDateTime zonedDateTimeOf = ZonedDateTime.of(dateOf, timeOf, ZoneId.of("Asia/Seoul"));

//2022-10-12T13:16:30.349447200+09:00[Asia/Seoul]
System.out.println("zonedDateTimeNow = " + zonedDateTimeNow);
System.out.println("UTC와 시차 : " + zonedDateTime.getOffset()); //+09:00
System.out.println("Zone 정보 : " + zonedDateTime.getZone()); //Asia/Seoul

 

2. 조작 메서드 : withXX(), plusXX(), minusXX()

1) 날짜 조작 

LocalDate localDate = LocalDate.now();
LocalDateTime localDateTime = LocalDateTime.now();
//날짜 더하거나 빼기
        .plusYears(long)       // 년도 더하기
        .minusYears(long)      // 년도 빼기
        .plusMonths(long)      // 월 더하기 
        .minusMonths(long)     // 월 빼기
        .plusDays(long)        // 일 더하기 
        .minusDays(long)       // 일 빼기
        .plusWeeks(long)       // 주 더하기
        .minusWeeks(long);     // 주 빼기
//날짜 변경 
        .withYear(int)          // 년도를 변경
        .withMonth(int)         // 월 변경
        .withDayOfMonth(int)    // 월의 일을 변경
        .withDayOfYear(int);    // 년도의 일을 변경
        .with(TemporalAdjuster adjuster) // 현재 날짜를 기준으로 상대적인 날짜로 변경

 

2) 시간 조작

LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
//시간 더하거나 빼기 
        .plusHours(long)       // 시간 더하기
        .minusHours(long)      // 시간 빼기
        .plusMinutes(long)     // 분 더하기 
        .minusMinutes(long)    // 분 빼기
        .plusSeconds(long)     // 초 더하기 
        .minusSeconds(long)    // 초 빼기
        .plusNanos(long)       // 나노초 더하기
        .minusNanos(long);     // 나노초 빼기
//시간 변경 
        .withHour(int)      // 시간 변경
        .withMinute(int)    // 분 변경
        .withSecond(int)    // 초 변경
        .withNano(int);     // 나노초 변경

 

3. 비교 메서드 : isAfter(), isBefore(), isEqual()

1) 날짜 비교 

LocalDate startDate = LocalDate.of(2016, 4, 2); 
LocalDate endDate = LocalDate.of(2016, 5, 5);

// startDateTime이 endDateTime 보다 이전 날짜 인지 비교
startDateTime.isBefore(endDateTime);    // true
// 동일 날짜인지 비교
startDateTime.isEqual(endDateTime); // false
// startDateTime이 endDateTime 보다 이후 날짜인지 비교
startDateTime.isAfter(endDateTime); // false

//사이 기간 계산 
Period period = startDate.until(endDate);
period.getYears();      // 0년
period.getMonths();     // 1개월
period.getDays();       // 3일 차이
ChronoUnit.DAYS.between(startDate, endDate); // 결과 : 33 (1개월 3일)

 

2) 시간 비교

LocalTime startTime = LocalTime.of(23, 52, 35);
LocalTime endTime = LocalTime.of(23, 59, 59);

// startTime이 endTime 보다 이전 시간 인지 비교
startTime.isBefore(endTime);    // true
// startTime이 endTime 보다 이후 시간 인지 비교
startTime.isAfter(endTime); // false

//사이 시간 계산 
Duration duration = Duration.between(startTime, endTime);
duration.getSeconds();      // 초의 차이
duration.getNano();         // 나노초의 차이

 

4. 날짜, 시간 <-> String 변환 : format(), parse()

LocalDateTime localDateTime = LocalDateTime.now();
//LocalDateTime->String 
localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//String->LocalDateTime
localDateTime.parse("2021-09-16 17:51:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

 

5. 활용 문제

import java.time.LocalDate;

//요일 구하는 문제 
class Solution {
    public String solution(int a, int b) {
        LocalDate date = LocalDate.of(2016, a, b);
        return date.getDayOfWeek().toString().substring(0,3);
    }
}
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

//특정 시간으로부터 60초가 지났는지 확인하는 문제 
class Solution {
    public String solution(int n) {
        String time = "10:10:00"; 
        String time2 = "10:11:01";
        LocalTime t1 = LocalTime.parse(time, DateTimeFormatter.ISO_LOCAL_TIME); //hh:MM:ss 형식 
        LocalTime t2 = LocalTime.parse(time2, DateTimeFormatter.ISO_LOCAL_TIME);
        if(t2.isAfter(t1.plusSeconds(59))){ // t2가 t1 이후로 60초가 지난 시간인지 확인
            //t1 이후로 60초가 지나서 sidecar가 발동된 시간을 String으로 변환해서 return 
            return lt1.plusSeconds(60).format(DateTimeFormatter.ISO_LOCAL_TIME));
        }
    }
}