Notice
Recent Posts
Recent Comments
Link
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Tags more
Archives
Today
Total
관리 메뉴

프로그래밍 공부

[자바] #23. 날짜/시간 관련 클래스들 본문

자바

[자바] #23. 날짜/시간 관련 클래스들

하 냥 2025. 2. 23. 04:45

1️⃣ LocalDate

날짜(연, 월, 일)를 표현하고, 시간 정보는 포함하지 않는다.

(ex. 2025-02-22)

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // 현재 날짜 가져오기
        LocalDate today = LocalDate.now();
        System.out.println("오늘 날짜: " + today);

        // 특정 날짜 생성
        LocalDate specificDate = LocalDate.of(2025, 2, 22);
        System.out.println("특정 날짜: " + specificDate);

        // 날짜 연산
        LocalDate nextWeek = today.plusWeeks(1);
        System.out.println("1주 후 날짜: " + nextWeek);

        // 날짜 정보 추출
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        System.out.println("연: " + year + ", 월: " + month + ", 일: " + day);
    }
}

2️⃣ LocalTime

시간을 시, 분, 초, 나노초 단위로 표현하고, 날짜 정보는 포함하지 않는다.

(ex, 14:30:15)

import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        // 현재 시간 가져오기
        LocalTime now = LocalTime.now();
        System.out.println("현재 시간: " + now);

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

        // 시간 연산
        LocalTime oneHourLater = now.plusHours(1);
        System.out.println("1시간 후: " + oneHourLater);

        // 시간 정보 추출
        int hour = now.getHour();
        int minute = now.getMinute();
        int second = now.getSecond();
        System.out.println("시: " + hour + ", 분: " + minute + ", 초: " + second);
    }
}

3️⃣ LocalDateTime

날짜와 시간을 함께 표현한다.

(ex. 2025-02-22T14:30:15)

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        // 현재 날짜 및 시간 가져오기
        LocalDateTime now = LocalDateTime.now();
        System.out.println("현재 날짜 및 시간: " + now);

        // 특정 날짜 및 시간 생성
        LocalDateTime specificDateTime = LocalDateTime.of(2025, 2, 22, 14, 30, 15);
        System.out.println("특정 날짜 및 시간: " + specificDateTime);

        // 날짜 및 시간 연산
        LocalDateTime nextDaySameTime = now.plusDays(1);
        System.out.println("내일 같은 시간: " + nextDaySameTime);

        // 날짜 및 시간 정보 추출
        int year = now.getYear();
        int hour = now.getHour();
        System.out.println("연도: " + year + ", 시: " + hour);
    }
}

📚 Period

📅 날짜 기반의 기간을 나타낸다.

연도(years), 월(months), 일(days) 단위로 기간을 표현.

import java.time.LocalDate;
import java.time.Period;

public class Main {
    public static void main(String[] args) {
        // Period 생성
        Period period = Period.of(2, 3, 10);  // 2년 3개월 10일
        System.out.println("Period: " + period);

        // 두 날짜 간의 기간 계산
        LocalDate startDate = LocalDate.of(2023, 1, 1);
        LocalDate endDate = LocalDate.of(2025, 4, 11);
        Period between = Period.between(startDate, endDate);
        System.out.println("시작일부터 종료일까지 기간: " + between);

        // Period를 날짜에 더하기
        LocalDate newDate = startDate.plus(period);
        System.out.println("시작일에 기간 더한 날짜: " + newDate);

        // Period 정보 추출
        System.out.println("연도: " + between.getYears() + ", 월: " + between.getMonths() + ", 일: " + between.getDays());
    }
}
Period: P2Y3M10D
시작일부터 종료일까지 기간: P2Y3M10D
시작일에 기간 더한 날짜: 2025-04-11
연도: 2, 월: 3, 일: 10

📚 Duration

시간 기반의 기간을 나타낸다.

초(seconds) 및 나노초(nanoseconds) 단위로 기간을 표현.

import java.time.Duration;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        // Duration 생성
        Duration duration = Duration.ofHours(5).plusMinutes(30); // 5시간 30분
        System.out.println("Duration: " + duration);

        // 두 시간 간의 기간 계산
        LocalTime startTime = LocalTime.of(9, 0);
        LocalTime endTime = LocalTime.of(15, 45);
        Duration between = Duration.between(startTime, endTime);
        System.out.println("시작 시간부터 종료 시간까지 기간: " + between);

        // Duration을 시간에 더하기
        LocalTime newTime = startTime.plus(duration);
        System.out.println("시작 시간에 기간 더한 시간: " + newTime);

        // Duration 정보 추출
        System.out.println("총 시간: " + between.toHours() + "시간, 추가 분: " + between.toMinutesPart() + "분");
    }
}
Duration: PT5H30M
시작 시간부터 종료 시간까지 기간: PT6H45M
시작 시간에 기간 더한 시간: 14:30
총 시간: 6시간, 추가 분: 45분

🎈 ZoneId

시간대를 나타내는 클래스.

전 세계 표준 시간대(Europe/Paris, Asia/Seoul, America/New_York 등)를 식별하는 ID를 제공한다.

시간대 정보를 기반으로 ZonedDateTime과 같은 날짜/시간 객체를 생성할 때 사용된다.
시간대 변경 및 시간대 간의 변환에 필수적!

 

🛠️ 주요 메서드

 

  • ZoneId.of(String zoneId): 주어진 문자열을 기반으로 ZoneId 인스턴스를 생성
  • ZoneId.systemDefault(): 시스템의 기본 시간대를 반환
  • getId(): 시간대 ID를 반환

 

import java.time.ZoneId;

public class ZoneIdExample {
    public static void main(String[] args) {
        // 시스템 기본 시간대
        ZoneId systemZone = ZoneId.systemDefault();
        System.out.println("System Default Zone: " + systemZone);

        // 특정 시간대 설정
        ZoneId seoulZone = ZoneId.of("Asia/Seoul");
        System.out.println("Asia/Seoul Zone: " + seoulZone);
    }
}
System Default Zone: Asia/Seoul
Asia/Seoul Zone: Asia/Seoul

🎈 ZoneDateTime

날짜(LocalDate), 시간(LocalTime), 시간대(ZoneId)를 모두 포함하는 불변형(immutable) 날짜-시간 클래스.

시간대가 포함된 정확한 날짜와 시간을 나타낸다.

시간대 간 시간 계산 및 변환을 지원한다.
국제적인 애플리케이션에서 각 지역의 로컬 시간과의 변환에 유용!

 

🛠️ 주요 메서드

  • ZonedDateTime.now(): 시스템 기본 시간대의 현재 날짜 및 시간 반환
  • ZonedDateTime.now(ZoneId zone): 특정 시간대의 현재 날짜 및 시간 반환
  • ZonedDateTime.of(LocalDate date, LocalTime time, ZoneId zone): 날짜, 시간, 시간대를 기반으로 인스턴스 생성
  • withZoneSameInstant(ZoneId zone): 같은 순간의 시간을 다른 시간대의 시간으로 변환
import java.time.ZonedDateTime;
import java.time.ZoneId;
import java.time.LocalDateTime;

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        // 시스템 기본 시간대의 현재 날짜 및 시간
        ZonedDateTime now = ZonedDateTime.now();
        System.out.println("Current DateTime with System Zone: " + now);

        // 특정 시간대의 현재 날짜 및 시간
        ZonedDateTime seoulTime = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
        System.out.println("Current DateTime in Seoul: " + seoulTime);

        // 다른 시간대 변환
        ZonedDateTime newYorkTime = seoulTime.withZoneSameInstant(ZoneId.of("America/New_York"));
        System.out.println("Same Instant in New York: " + newYorkTime);

        // 특정 날짜, 시간, 시간대 설정
        LocalDateTime dateTime = LocalDateTime.of(2025, 3, 15, 10, 30);
        ZonedDateTime customZonedDateTime = ZonedDateTime.of(dateTime, ZoneId.of("Europe/London"));
        System.out.println("Custom ZonedDateTime in London: " + customZonedDateTime);
    }
}
Current DateTime with System Zone: 2025-02-23T14:35:47.123+09:00[Asia/Seoul]
Current DateTime in Seoul: 2025-02-23T14:35:47.125+09:00[Asia/Seoul]
Same Instant in New York: 2025-02-23T00:35:47.125-05:00[America/New_York]
Custom ZonedDateTime in London: 2025-03-15T10:30+00:00[Europe/London]