JAVA/포스팅

java.time.Clock 클래스

짜집퍼박사(짜박) 2023. 11. 17. 15:09

java.time.Clock 클래스는 날짜와 시간을 가져오는 데 사용되는 추상 클래스입니다. 이 클래스는 Java 8에서 java.util.Date 및 System.currentTimeMillis() 대안으로 소개되었으며, java.time 패키지에서 다양한 시간 기반 작업을 수행하는 데 사용됩니다.

 

1. Clock 클래스의 주요 메서드

 

instant() 메서드

Clock 객체의 현재 시각을 나타내는 Instant를 반환합니다.

millis() 메서드

현재 시각을 밀리초로 반환합니다.

getZone() 메서드

Clock 객체가 사용하는 시간대(ZoneId)를 반환합니다.

withZone(ZoneId zone) 메서드

새로운 시간대로 Clock 객체를 복제합니다.

 

Clock 사용 예제

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;

public class ClockExample {
    public static void main(String[] args) {
        // 시스템 기본 시계를 사용하여 Clock 객체 생성
        Clock systemClock = Clock.systemDefaultZone();

        // 현재 시각 (Instant) 가져오기
        Instant currentInstant = systemClock.instant();
        System.out.println("Current Instant: " + currentInstant);

        // 밀리초로 현재 시각 가져오기
        long currentMillis = systemClock.millis();
        System.out.println("Current Milliseconds: " + currentMillis);

        // 시간대 확인
        ZoneId zoneId = systemClock.getZone();
        System.out.println("Time Zone: " + zoneId);

        // 다른 시간대로 변경
        Clock clockInNewZone = systemClock.withZone(ZoneId.of("America/New_York"));
        System.out.println("Clock in New Zone: " + clockInNewZone);
    }
}

이 예제에서는 Clock 클래스를 사용하여 현재 시각과 시간대를 확인하고, 새로운 시간대로 변경하는 방법을 보여줍니다. Clock는 특정 시간대를 기반으로 시각을 얻는 데 사용됩니다. 코드에서는 기본 시스템 시계를 사용하도록 설정했습니다.

 

With ChatGPT