Instant
는 UTC(협정 세계시)를 기준으로하는, 시간의 한 지점을 나타낸다.
날짜와 시간을 나노초 정밀도로 표현하며, UTC 기준(1970년 1월 1일 0시 0분 0초)으로 경과한 시간으로 계산된다. 초 데이터이기 때문에 날짜와 시간을 계산하는 데에는 적합하지 않다.
즉, 에포크 시간(Epoch time)을 다루는 클래스이다.
public final class Instant
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {
...
private final long seconds;
private final int nanos;
...
}
메서드 | 설명 |
---|---|
now() | 현재 UTC 기준의 Instant 객체 반환 |
ofEpochSecond(long epochSecond) | 주어진 에포크 초 값을 기준으로 Instant 객체 반환 |
getEpochSecond() | UTC 기준으로 흐른 초 반환 |
plusSeconds(long secondsToAdd) | 현재 Instant에 주어진 초를 더하여 새로운 Instant 객체 반환 |
minusSeconds(long secondsToSubtract) | 현재 Instant에서 주어진 초를 빼서 새로운 Instant 객체 반환 |
toEpochMilli() | Instant 객체를 에포크 밀리초 값으로 반환 |
atZone(ZoneId zone) | Instant 객체를 주어진 시간대의 ZonedDateTime으로 변환하여 반환 |
public class InstantMain {
public static void main(String[] args) {
// 1. Instant 생성
// 1-1. now
Instant now = Instant.now();
System.out.println("현재: " + now);
// 1-2. ZonedDateTime + from
ZonedDateTime zonedDt = ZonedDateTime.now();
Instant from = Instant.from(zonedDt);
System.out.println("타임존: " + from);
// 1-3. ofEpochSecond
Instant epoch = Instant.ofEpochSecond(0);
System.out.println("지정: " + epoch);
// 2. Instant 계산
Instant later = epoch.plusSeconds(3600);
System.out.println("1시간 후(Instant): " + later);
// 3. Instant 조회
long laterEpoch = later.getEpochSecond();
System.out.println("1시간 후(초): " + laterEpoch);
// 4. Instant -> ZonedDateTime 변환
ZonedDateTime zonedDateTime = later.atZone(ZoneId.of("Asia/Seoul"));
System.out.println("Instant를 서울 시간대로 변환: " + zonedDateTime);
}
}
현재: 2024-06-03T16:06:43.186964Z
타임존: 2024-06-03T16:06:43.202648Z
지정: 1970-01-01T00:00:00Z
1시간 후(Instant): 1970-01-01T01:00:00Z
1시간 후(초): 3600
Instant를 서울 시간대로 변환: 1970-01-01T10:00+09:00[Asia/Seoul]