JAVA
JAVA Instant
James Arthur Gosling
2023. 4. 11. 18:47
Java에서 Instant 클래스는 시간(time)을 나타내는 클래스입니다. 이 클래스는 지정된 초(second) 및 나노초(nanosecond) 단위의 시간을 나타내며, 해당 시간은 1970년 1월 1일 0시 0분 0초(UTC)로부터 경과된 시간을 나타냅니다.
Instant 클래스는 java.time 패키지에서 제공되며, Java 8 이상에서 사용할 수 있습니다. 이 클래스는 불변(immutable)이기 때문에, 한번 생성된 Instant 객체는 수정될 수 없습니다.
Instant 클래스의 생성자는 여러 가지가 제공됩니다. Instant.now()를 사용하면 현재 시간을 나타내는 Instant 객체를 생성할 수 있습니다. Instant.ofEpochSecond(long epochSecond) 또는 Instant.ofEpochSecond(long epochSecond, long nanoAdjustment)를 사용하면 지정된 초 또는 초와 나노초로부터 Instant 객체를 생성할 수 있습니다.
Instant 클래스는 Date나 Calendar와 같은 더 오래된 Java 날짜 및 시간 API와 호환됩니다. 따라서 이전 Java 버전에서 작성된 코드와 Java 8 이상에서 작성된 코드를 함께 사용할 수 있습니다.Instant 클래스를 사용하는 방법에 대해서는 다음과 같습니다
- Instant 객체 생성하기
- Instant.now(): 현재 시간을 나타내는 Instant 객체를 생성합니다.
- Instant.ofEpochSecond(long epochSecond): 지정된 초로부터 Instant 객체를 생성합니다.
- Instant.ofEpochSecond(long epochSecond, long nanoAdjustment): 지정된 초와 나노초로부터 Instant 객체를 생성합니다.
- Instant 객체 사용하기
- getEpochSecond(): Instant 객체가 나타내는 시간을 초로 반환합니다.
- getNano(): Instant 객체가 나타내는 시간에서 초 이하의 부분을 나노초로 반환합니다.
- plus(Duration duration): Instant 객체에 지정된 Duration 값을 더한 결과를 반환합니다.
- minus(Duration duration): Instant 객체에서 지정된 Duration 값을 뺀 결과를 반환합니다.
- isBefore(Instant otherInstant): Instant 객체가 otherInstant보다 이전인지 여부를 반환합니다.
- isAfter(Instant otherInstant): Instant 객체가 otherInstant보다 이후인지 여부를 반환합니다.
- Instant 객체 출력하기
- toString(): Instant 객체를 문자열로 반환합니다. 이 문자열은 ISO-8601 형식으로 출력됩니다.
아래는 Instant 클래스를 사용한 예제 코드입니다.
import java.time.Instant;
import java.time.Duration;
public class InstantExample {
public static void main(String[] args) {
// 현재 시간을 나타내는 Instant 객체 생성하기
Instant now = Instant.now();
System.out.println("현재 시간: " + now);
// 5초 후의 시간을 나타내는 Instant 객체 생성하기
Instant later = now.plus(Duration.ofSeconds(5));
System.out.println("5초 후의 시간: " + later);
// 10초 전의 시간을 나타내는 Instant 객체 생성하기
Instant earlier = now.minus(Duration.ofSeconds(10));
System.out.println("10초 전의 시간: " + earlier);
// 두 Instant 객체 간 비교하기
boolean isBefore = earlier.isBefore(now);
System.out.println("earlier가 now보다 이전인가요? " + isBefore);
boolean isAfter = later.isAfter(now);
System.out.println("later가 now보다 이후인가요? " + isAfter);
}
}
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
현재 시간: 2023-04-11T08:00:00.000000Z
5초 후의 시간: 2023-04-11T08:00:05.000000Z
10초 전의 시간: 2023-04-11T07:59:50.000000Z
earlier가 now보다 이전인가요? true
later가 now보다 이후인가요? true