Java
Instant
Wanderer Kim
2025. 5. 23. 18:41
728x90
Instant란?
Isntant는 UTC를 기준으로 하는, 시간의 한 지점을 나타낸다. Instant는 날짜와 시간을 나노초 정밀도로 표현하며, 1970년 1월 1일 0시 0분 0초를 기준으로 통과한 시간을 계산한다.
즉, Instant 내부에는 초 데이터만 들어있다. 따라서 날짜와 시간을 사용해야 할 때 적합하지 않다.
public class Instant {
private final long seconds;
private final int nanos;
...
}
Epoch 시간
epoch time 또는 unix timestamp 는 컴퓨터 시스템에서 시간을 나타내는 방법 중 하나이다. 이는 1970년 1월 1일 00:00:00부터 현재까지 경과된 시간을 초 단위로 표현한 것이다. 즉, unix 시간은 1970년 1월 1일 이후로 경과한 전체 초로 수로, 시간대에 영향을 받지 않는 절대적인 시간 표현 방법이다.
Instant는 epoch시간을 다루는 클래스이다.ㅁ
- 장점
- 시간대 독립성: Instant를 UTC를 기준으로 하므로, 시간대에 영향을 받지 않는다.
- 고정된 기준점: 모든 Instant는 1970년 1월 1일 00:00:00을 기준으로 하므로 시간 계산 및 비교가 명확하고 일관된다.
- 단점
- 사용자 친화적이지 않음: Instant는 사람이 읽고 이해하기에는 직관적이지 않는다.
- 시간대 정보 부재: Instant에는 시간대 정보가 포함되어 있지 않아, 특정 지역의 날짜와 시간으로 변환하면 추가적인 작업이 필요하다.
- 사용 예
- 전 세계적인 시간 기준 필요 시
- 시간대 변환 없이 시간 계산 필요 시
- 데이터 저장 및 교환
사용 예제 코드
package time;
import java.time.Instant;
import java.time.ZonedDateTime;
public class InstantMain {
public static void main(String[] args) {
//생성
Instant now = Instant.now(); //UTC 기준
System.out.println("now = " + now);
ZonedDateTime zdt = ZonedDateTime.now();
Instant from = Instant.from(zdt);
System.out.println("from = " + from);
Instant epochStart = Instant.ofEpochSecond(0);
System.out.println("epochStart = " + epochStart);
//계산
Instant later = epochStart.plusSeconds(3600);
System.out.println("later = " + later);
//조회
long laterEpochSecond = later.getEpochSecond();
System.out.println("laterEpochSecond = " + laterEpochSecond);
}
}
now = 2024-02-13T06:46:07.101393Z
from = 2024-02-13T06:46:07.117732Z
epochStart = 1970-01-01T00:00:00Z
later = 1970-01-01T01:00:00Z
laterEpochSecond = 3600
- now(): UTC 기준 현재 시간의 Instant를 생성한다.
- from(): 다른 타입의 날짜와 시간을 기준으로 Instant를 생성한다.
- ofEpochSecond(): epoch 시간을 기준으로 Instant를 생성한다. 0초를 선택하면 epoch 시간인 1970년 1월 1일 0시 0분 0초로 생성한다.
- plusXXX(): 시간, 분, 초를 더한다. e.g. plusSeconds()
- getEpochSecond(): epoch 시간인 1970년 1월 1일 0시 0분 0초를 기준으로 흐른 초르 반환한다.
반응형