본문 바로가기
우아한 코딩

자바 프로그래밍에서의 효율적인 날짜와 시간 다루기

by 피크인사이트 2024. 2. 6.
반응형

- JDK 8 이후의 날짜와 시간 -

자바에서는 JDK의 Date와 Calendar 클래스로 날짜와 시간을 다루기 불편한 것으로 악명이 높았었습니다.
그것을 해결하기 위해 Joda-Time과 같은 오픈소스 라이브러리가 등장하였으며, 마침내 JDK 8 부터 향상된 API가 제공되어 편리하고 정확하게 날짜와 시간 다루기가 가능해졌습니다.

 

이 글에서는 JDK 8 이후의 API를 사용하여 날짜와 시간을 쉽게 다루는 방법과 자주 사용되는 클래스들을 예시 코드를 통해 알아보겠습니다.

lt;JDK 8 이후의 날짜와 시간 API



자바에서 사용되는 날짜와 시간 API 종류

[java.util.Date]
자바에서 가장 기본적인 날짜와 시간 클래스이지만 여러 가지 문제점이 있어서 현재는 많이 사용되지 않습니다.
[java.util.Calendar]
날짜와 시간을 설정하거나 계산하는데 유용합니다.
[java.text.SimpleDateFormat]
날짜를 텍스트로, 텍스트를 날짜로 변환하는 데 사용되는 클래스입니다.
[java.time 패키지]
자바 8부터 추가된 날짜/시간 API입니다. 이 패키지에 LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration 등의 클래스가 있습니다. 이 API는 불변 객체를 사용하므로 안전하며, 사용하기에 훨씬 편리하고 직관적입니다.


java.time 패키지를 이용한 다양한 코딩 사례

java.time 패키지는 자바 8부터 추가되어 가장 널리 이용되는 패키지로 불변성(Immutability), 스레드 안정성(Thread Safety), 설계의 명확성 등과 같은 장점을 가지고 있으며, 날짜, 시간, 기간, 간격, 시간대(Time Zone) 등을 다루는 다양한 클래스와 메서드를 포함하고 있습니다.
java.time  패키지에 포함된 주요 클래스들을 코딩 예시를 통해 알아보겠습니다.

 

1. LocalDate

LocalDate 클래스는 날짜 정보만을 나타내는 클래스로, 시간 정보를 포함하지 않습니다.

이 클래스는 시간대를 고려하지 않는 로컬 날짜를 표현합니다. 
다음은 LocalDate를 사용하는 예시 코드입니다

       // 현재 날짜 가져오기
        LocalDate currentDate = LocalDate.now();
        System.out.println("현재 날짜: " + currentDate);

       // 특정 날짜 생성하기
        LocalDate specificDate = LocalDate.of(2023, 9, 15);
        System.out.println("특정 날짜: " + specificDate);

        // 날짜간의 차이 계산하기
        LocalDate futureDate = specificDate.plusYears(1).plusMonths(3).plusDays(5);
        System.out.println("특정 날짜로부터 1년 3개월 5일 후: " + futureDate);

        // 날짜 비교하기
        if (currentDate.isAfter(specificDate)) {
            System.out.println("현재 날짜가 특정 날짜보다 늦은 날짜입니다.");
        } else if (currentDate.isBefore(specificDate)) {
            System.out.println("현재 날짜가 특정 날짜보다 이른 날짜입니다.");
        } else {
            System.out.println("현재 날짜와 특정 날짜가 같습니다.");
        }

       // 날짜의 요소(연도, 월, 일)에 접근하기 
        int year = specificDate.getYear();
        int month = specificDate.getMonthValue();
        int day = specificDate.getDayOfMonth();
        System.out.println("연도: " + year + ", 월: " + month + ", 일: " + day);

        // 날짜의 요일 가져오기
        System.out.println("특정 날짜의 요일: " + specificDate.getDayOfWeek());


2. LocalTime

LocalTime 클래스는 날짜를 포함하지 않고 시간 정보만을 나타내는 클래스입니다. 이 클래스는 시간대를 고려하지 않는 로컬 시간을 표현합니다. 예를 들어, 오후 3시 30분을 나타내거나, 오전 10시 15분을 나타낼 수 있습니다.
아래는 LocalTime을 사용하는 예시 코드입니다.

 

       // 현재 시간 가져오기
        LocalTime currentTime = LocalTime.now();
        System.out.println("현재 시간: " + currentTime);

        // 특정 시간 생성하기
        LocalTime specificTime = LocalTime.of(14, 30, 45);
        System.out.println("특정 시간: " + specificTime);

        // 시간 간의 차이 계산하기
        LocalTime futureTime = specificTime.plusHours(2).plusMinutes(15);
        System.out.println("특정 시간으로부터 2시간 15분 후: " + futureTime);

        // 시간 비교하기
        if (currentTime.isAfter(specificTime)) {
            System.out.println("현재 시간이 특정 시간보다 늦은 시간입니다.");
        } else if (currentTime.isBefore(specificTime)) {
            System.out.println("현재 시간이 특정 시간보다 이른 시간입니다.");
        } else {
            System.out.println("현재 시간과 특정 시간이 같습니다.");
        }

        // 시간의 요소(시, 분, 초)에 접근하기
        int hour = specificTime.getHour();
        int minute = specificTime.getMinute();
        int second = specificTime.getSecond();
        System.out.println("시: " + hour + ", 분: " + minute + ", 초: " + second);


3. LocalDateTime

LocalDateTime은 날짜와 시간 정보를 모두 포함하는 클래스입니다. 여기에는 시간대(Time Zone) 정보가 포함되어 있지 않으며, 로컬 날짜와 시간을 나타냅니다.
아래는 LocalDateTime을 사용하는 예시 코드입니다

        // 현재 날짜와 시간 가져오기
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("현재 날짜와 시간: " + currentDateTime);

        // 특정 날짜와 시간 생성하기
        LocalDateTime specificDateTime = LocalDateTime.of(2023, 9, 15, 14, 30, 45);
        System.out.println("특정 날짜와 시간: " + specificDateTime);

        // 날짜와 시간 간의 차이 계산하기
        LocalDateTime futureDateTime = specificDateTime.plusYears(1).plusMonths(3).plusDays(5)
                                            .plusHours(2).plusMinutes(15).plusSeconds(30);
        System.out.println("특정 날짜와 시간으로부터 1년 3개월 5일 2시간 15분 30초 후: " + futureDateTime);

        // 날짜와 시간 비교하기
        if (currentDateTime.isAfter(specificDateTime)) {
            System.out.println("현재 날짜와 시간이 특정 날짜와 시간보다 늦은 시간입니다.");
        } else if (currentDateTime.isBefore(specificDateTime)) {
            System.out.println("현재 날짜와 시간이 특정 날짜와 시간보다 이른 시간입니다.");
        } else {
            System.out.println("현재 날짜와 시간이 특정 날짜와 시간과 같습니다.");
        }

        // 날짜와 시간의 요소(연도, 월, 일, 시, 분, 초)에 접근하기
        int year = specificDateTime.getYear();
        int month = specificDateTime.getMonthValue();
        int day = specificDateTime.getDayOfMonth();
        int hour = specificDateTime.getHour();
        int minute = specificDateTime.getMinute();
        int second = specificDateTime.getSecond();
        System.out.println("날짜와 시간의 요소 출력")  ;


4. ZonedDateTime

ZonedDateTime은 시간대(Time Zone) 정보를 포함하는 클래스로써 날짜와 시간을 특정 시간대에 매핑하는 기능을 가지고 있으며, LocalDateTime과 ZoneId를 조합하여 사용됩니다.

        // 현재날짜와 시간을 기본 시간대로 가져오기
        ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
        System.out.println("현재 날짜와 시간: " + currentZonedDateTime);

        // 특정시간을 특정시간대로 생성하기
        LocalDateTime localDateTime = LocalDateTime.of(2023, 9, 15, 14, 30, 45);
        ZoneId zoneId = ZoneId.of("America/New_York"); // 뉴욕 시간대
        ZonedDateTime specificZonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
        System.out.println("특정 날짜와 시간: " + specificZonedDateTime);

        // 날짜와 시간간의 차이 계산
        ZonedDateTime futureZonedDateTime = specificZonedDateTime.plusYears(1).plusMonths(3).plusDays(5)
                                            .plusHours(2).plusMinutes(15).plusSeconds(30);
        System.out.println("특정 날짜와 시간으로부터 1년 3개월 5일 2시간 15분 30초 후: " + futureZonedDateTime);

       // 날짜와 시간의 요소(연도, 월, 일 등)에 접근하기
        int year = specificZonedDateTime.getYear();
        int month = specificZonedDateTime.getMonthValue();
        int day = specificZonedDateTime.getDayOfMonth();
        int hour = specificZonedDateTime.getHour();
        int minute = specificZonedDateTime.getMinute();
        int second = specificZonedDateTime.getSecond();
        System.out.println( ....;

        // 시간대 정보 가져오기
        ZoneId zone = specificZonedDateTime.getZone();
        System.out.println("특정 시간대: " + zone);

 

5. Duration 및 Period 비교

① Duration

먼저 Duration 클래스는 두 시간 간의 차이를 표현하는 데 사용됩니다.

이 클래스는 시간의 길이를 초 단위로 나타냅니다.

 

       // 두 시간간의 차이 계산
        LocalTime start = LocalTime.of(9, 0);
        LocalTime end = LocalTime.of(11, 30);      

        Duration duration = Duration.between(start, end);
        long hours = duration.toHours(); // 시간으로..
        long minutes = duration.toMinutes(); // 분으로..       

        System.out.println("시작: " + start);
        System.out.println("종료: " + end);
        System.out.println("간격: " + hours + " 시간 " + (minutes % 60) + " 분");       

       // Duration을 사용한 시간 게산
        LocalTime newTime = start.plus(duration);
        System.out.println("새로운 시간: " + newTime);

 

② Period

Period 클래스는 두 날짜 간의 차이를 표현하는 데 사용됩니다.

이 클래스는 년(year) , 일(day), 월(month) 단위의 차이를 표현할 수 있습니다.
Period를 사용하는 예시 코드 :

        // 두 날짜 간의 차이 계산하기
        LocalDate start_Date = LocalDate.of(2023, 9, 15);
        LocalDate end_Date = LocalDate.of(2025, 3, 20);
        Period period = Period.between(start_Date, end_Date);
        int p_years = period.getYears();
        int p_months = period.getMonths();
        int p_days = period.getDays();
        System.out.println("시작 날짜: " + start_Date);
        System.out.println("종료 날짜: " + end_Date);
        System.out.println("날짜 간격: " + p_years + "년 " + p_months + "개월 " + p_days + "일");
     
        // Period를 사용하여 날짜를 더하거나 빼기
        LocalDate newDate = start_Date.plus(period);
        System.out.println("새로운 날짜: " + newDate);

맺음말

이상으로 자바 프로그램에서 반드시 알고 가야 할 날짜와 시간을 다루는 클래스들을 살펴보았습니다.

그중에서도 가장 최근에 도입된 java.time 패키지를 사례를 들어 쉽게 알아보았습니다.
그러나 위와 같이 비교적 쉽게 코딩이 가능한 클래스들도 반드시 지켜야 할 주의사항들이 있습니다.
불변성을 잘 유지해야 되고 사용하는 시간대를 고려해서 적절한 클래스를 사용해야 되며 예외처리 또한 신경 써야 합니다.

다음 글에서는 날짜와 시간을 다루는 프로그램 코딩 시 주의해야 할 사항을 예시를 들어 설명할 예정입니다.

감사합니다.

반응형