[Java][time] Instant 클래스

2022. 6. 16. 17:16JAVA/Language

Instant 클래스

Instant 클래스는 에포크 타임(EPOCH TIME, 1970-01-01 00:00:00 UTC)부터 경과된 시간을 나노초 단위로 표현하는 클래스입니다. 

		Instant now = Instant.now();
		Instant now2 = Instant.ofEpochSecond(now.getEpochSecond());
		Instant now3 = Instant.ofEpochSecond(now.getEpochSecond(), now.getNano());
		
		System.out.println(now);  // 2022-06-16T08:00:18.794332300Z
		System.out.println(now2); // 2022-06-16T08:00:18Z
		System.out.println(now3); // 2022-06-16T08:00:18.794332300Z

Instant 클래스는 항상 UTC(+00:00)를 기준으로 하기 때문에, LocalTime 클래스와 차이가 있을 수 있습니다. 예를 들어 한국 시간은 시간대가 '+09:00'이므로 Instant 클래스와 LocalTime 클래스간에는 9시간의 차이가 있습니다.

 

UTC(Coordinated Universal Time)이란 무엇인가?

UTC는 '세계 협정시'이라고 하며, 1972년 1월 1일부터 시행된 국제 표준시입니다. 이전에 사용되던 GMT(Greenwich Mean Time)와 UTC는 거의 같지만, UTC가 좀더 정확하다고 합니다.

 

Instant와 Date간의 변환

Instant 클래스는 기존의 java.util.Date를 대체하기 위한 것이며, JDK 1.8부터 Date에 Instant로 변환할 수 있는 새로운 메서드가 추가되었습니다.

static Date from(Instant instant) // Instant -> Date
Instant toInstant()               // Date    -> Instant

 

References

source code : https://github.com/yonghwankim-dev/java_study/tree/main/ch10
[도서] Java의 정석, 남궁 성 지음