본문 바로가기
JAVA & KOTLIN

[JAVA] Java Instant 주요 메소드

by nozee 2024. 12. 24.
반응형

 

Java 8에서는 날짜와 시간을 다룰 수 있는 새로운 API인 java.time 패키지가 도입되었다. 이 중 Instant 클래스는 기계 시간(UTC 기준의 타임스탬프)을 표현하는 데 사용된다. 나노초 정밀도로 시간을 표현하며, 주로 타임스탬프 기반 작업에 유용하다다. 주요 메소드와 예제를 통해 살펴보겠습니다.

 

JAVA Time 관련 포스팅

2024.12.17 - [JAVA] - [JAVA] java 1.8에서 변경 된 time

 

[JAVA] java 1.8에서 변경 된 time

Java 8 이상이 되면서 Date, Calandar 등이 레거시가 되어 버리고 java.time의 Instant, LocalDateTime, ZoneDateTime이 추가되었다. Date, Calendar 클래스의 문제점불변 객체가 아니라 thread-safe 하지 않음날짜 단위의

nozee.tistory.com

 

주요 메소드와 사용 예시

1. now()

현재 UTC 기준의 시간을 반환된다.

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println("현재 시간 (UTC): " + now);
    }
}
 
현재 시간 (UTC): 2023-12-23T10:15:30.123Z

 

2. ofEpochSecond(long epochSecond)

Epoch(1970-01-01T00:00:00Z) 기준으로 초 단위의 시간을 Instant로 변환한다.

 
import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant instant = Instant.ofEpochSecond(1672531200); // 2023-01-01T00:00:00Z
        System.out.println("Epoch 기준 시간: " + instant);
    }
}

 

Epoch 기준 시간: 2023-01-01T00:00:00Z

 

 

3. plus() / minus()

Instant 객체에 시간을 더하거나 빼는 메소드.

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        Instant tenSecondsLater = now.plusSeconds(10); // 10초 추가
        Instant fiveMinutesBefore = now.minusSeconds(300); // 300초 (5분) 감소

        System.out.println("현재 시간: " + now);
        System.out.println("10초 후: " + tenSecondsLater);
        System.out.println("5분 전: " + fiveMinutesBefore);
    }
}
현재 시간: 2023-12-23T10:15:30.123Z
10초 후: 2023-12-23T10:15:40.123Z
5분 전: 2023-12-23T10:10:30.123Z

 

 

4. toEpochMilli()

Instant를 밀리초 단위로 변환합니다. 주로 데이터베이스나 외부 시스템과의 연동에서 유용합니다.

 
import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        long epochMilli = now.toEpochMilli(); // 현재 시간의 Epoch 밀리초 값

        System.out.println("Epoch 밀리초: " + epochMilli);
    }
}
Epoch 밀리초: 1703406930123

 

 

5. isBefore() / isAfter()

두 Instant 객체를 비교한다.

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant earlier = Instant.ofEpochSecond(1609459200); // 2021-01-01T00:00:00Z
        Instant later = Instant.now();

        System.out.println("Earlier가 Later보다 이전인가? " + earlier.isBefore(later));
        System.out.println("Later가 Earlier보다 이후인가? " + later.isAfter(earlier));
    }
}

 

Earlier가 Later보다 이전인가? true
Later가 Earlier보다 이후인가? true

 

 

 

6. parse(CharSequence text)

문자열 형식의 UTC 시간을 Instant로 변환한다.

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        String timestamp = "2023-12-23T10:15:30.123Z";
        Instant instant = Instant.parse(timestamp);

        System.out.println("Parsed Instant: " + instant);
    }
}
 
Parsed Instant: 2023-12-23T10:15:30.123Z

 

7. toString()

Instant 객체를 ISO-8601 형식의 문자열로 반환한다.

import java.time.Instant;

public class InstantExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println("Instant 문자열: " + now.toString());
    }
}
 
Instant 문자열: 2023-12-23T10:15:30.123Z

 

활용 시 주의점

  • Instant는 항상 UTC 기준입니다. 로컬 시간과 혼동하지 않도록 주의해야 합니다.
  • 로컬 시간과 변환하려면 ZoneId 및 ZonedDateTime 클래스와 함께 사용하세요.
 
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class InstantExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        ZonedDateTime zonedDateTime = now.atZone(ZoneId.systemDefault());

        System.out.println("현재 UTC 시간: " + now);
        System.out.println("현재 로컬 시간: " + zonedDateTime);
    }
}
 
현재 UTC 시간: 2023-12-23T10:15:30.123Z
현재 로컬 시간: 2023-12-23T19:15:30.123+09:00[Asia/Seoul]

Instant는 간결한 API로 정확한 타임스탬프 처리와 비교 작업을 제공합니다. 특히 로그 시스템, 분산 애플리케이션, 데이터베이스와의 작업에서 많이 사용된다.

 

긴 글 읽어 주셔서 감사합니다.
반응형