[java] 자바 11에서 추가된 Instant 클래스의 활용 방법

자바 11에서 도입된 Instant 클래스는 시간을 나타내는 불변(immutable) 타입으로, 날짜와 시간을 다루기 위해 사용됩니다. Instant 클래스는 특정 시간을 정확하게 표현하고 다양한 연산을 수행할 수 있는 기능을 제공합니다.

다음은 Instant 클래스를 활용하는 몇 가지 예제입니다.

현재 시간 가져오기

Instant now = Instant.now();
System.out.println("현재 시간: " + now);

특정 시간 대의 Instant 생성하기

String datetimeString = "2022-01-01T00:00:00Z";
Instant instant = Instant.parse(datetimeString);
System.out.println("지정된 시간: " + instant);

Instant 간의 차이 계산하기

Instant start = Instant.parse("2022-01-01T00:00:00Z");
Instant end = Instant.parse("2022-01-02T00:00:00Z");

Duration duration = Duration.between(start, end);
System.out.println("시간 차이: " + duration.toHours() + "시간");

지정된 시간으로부터 일정 시간 더하기

Instant now = Instant.now();

// 1시간 더하기
Instant added = now.plus(Duration.ofHours(1));
System.out.println("1시간 후: " + added);

// 1일 더하기
Instant added = now.plus(Duration.ofDays(1));
System.out.println("1일 후: " + added);

Instant를 다른 시간 단위로 변환하기

Instant now = Instant.now();

// Epoch Milliseconds로 변환
long epochMillis = now.toEpochMilli();
System.out.println("Epoch Milliseconds: " + epochMillis);

// Epoch Seconds로 변환
long epochSeconds = now.getEpochSecond();
System.out.println("Epoch Seconds: " + epochSeconds);

Instant 클래스의 활용 방법은 위의 예제를 통해 간단하게 설명하였습니다. Instant 클래스는 자바 11 이상에서 사용할 수 있으며, 날짜와 시간을 다루는 경우 편리하게 사용될 수 있습니다.

더 자세한 내용은 Java 11 API 문서를 참조하세요.