[java] Joda-Time으로 현재 시간을 특정 시간대로 변환하기
자바에서 날짜와 시간을 처리할 때 Joda-Time 라이브러리는 많은 유용한 기능을 제공합니다. 이 중에서 특정 시간대로 현재 시간을 변환하는 방법에 대해 알아보겠습니다.
Joda-Time 라이브러리 설치하기
Joda-Time을 사용하기 위해 먼저 해당 라이브러리를 설치해야 합니다. Maven을 사용하는 경우, pom.xml에 다음 디펜던시를 추가합니다.
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.11</version>
</dependency>
Gradle을 사용하는 경우, build.gradle 파일에 다음 디펜던시를 추가합니다.
implementation 'joda-time:joda-time:2.10.11'
현재 시간을 특정 시간대로 변환하기
다음은 Joda-Time을 사용하여 현재 시간을 특정 시간대로 변환하는 예제입니다.
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class TimeZoneExample {
public static void main(String[] args) {
// 현재 시간을 UTC로 생성
DateTime currentDateTime = new DateTime(DateTimeZone.UTC);
// 특정 시간대로 변환
DateTime convertedDateTime = currentDateTime.toDateTime(DateTimeZone.forID("Asia/Seoul"));
System.out.println("현재 시간 (UTC): " + currentDateTime);
System.out.println("변환된 시간 (Asia/Seoul): " + convertedDateTime);
}
}
이 예제에서는 DateTimeZone.UTC
를 사용하여 현재 시간을 UTC로 생성한 다음, toDateTime()
메서드를 사용하여 Asia/Seoul
시간대로 변환합니다. 결과로 현재 시간과 변환된 시간이 출력됩니다.