JAVA/포스팅

java.time.ZonedDateTime 클래스

짜집퍼박사(짜박) 2023. 11. 17. 00:41

java.time.ZonedDateTime 클래스는 지역 시간대 정보까지 포함한 날짜와 시간을 나타내는 클래스입니다. ZonedDateTime은 LocalDateTime과 ZoneId를 결합하여 특정 지역 시간대에 해당하는 날짜와 시간 정보를 제공합니다.

 

1. ZonedDateTime 객체 생성

현재 날짜와 시간으로 ZonedDateTime 객체 생성

ZonedDateTime currentDateTime = ZonedDateTime.now();

특정 날짜와 시간으로 ZonedDateTime 객체 생성

LocalDateTime localDateTime = LocalDateTime.of(2023, Month.FEBRUARY, 20, 15, 30);
ZoneId zoneId = ZoneId.of("Europe/Paris");
ZonedDateTime specificDateTime = ZonedDateTime.of(localDateTime, zoneId);

 

2. ZonedDateTime 객체에서 날짜와 시간 정보 가져오기

연, 월, 일, 시, 분, 초 정보 가져오기

int year = currentDateTime.getYear();
Month month = currentDateTime.getMonth();
int day = currentDateTime.getDayOfMonth();
int hour = currentDateTime.getHour();
int minute = currentDateTime.getMinute();
int second = currentDateTime.getSecond();

지역 시간대 정보 가져오기

ZoneId zone = currentDateTime.getZone();

 

3. ZonedDateTime 객체 연산

특정 기간을 더하거나 빼기

ZonedDateTime futureDateTime = currentDateTime.plusDays(7).plusHours(3);
ZonedDateTime pastDateTime = currentDateTime.minusMonths(2);

특정 값으로 변경하기

ZonedDateTime newDateTime = currentDateTime.withYear(2024).withMonth(6);

 

4. ZonedDateTime 객체 비교

다른 ZonedDateTime 객체와의 비교

boolean isAfter = currentDateTime.isAfter(specificDateTime);
boolean isBefore = currentDateTime.isBefore(specificDateTime);
int comparison = currentDateTime.compareTo(specificDateTime);

 

5. ZonedDateTime 객체의 출력

ZonedDateTime 객체를 문자열로 변환

String dateTimeAsString = currentDateTime.toString();

 

6. ZonedDateTime 객체의 형식화

사용자 정의 형식으로 날짜와 시간을 문자열로 변환

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");
String formattedDateTime = currentDateTime.format(formatter);

 

주의사항

- ZonedDateTime 클래스는 불변(immutable)이며, 변경할 수 없는 객체입니다. 따라서 ZonedDateTime 객체를 조작하는 메소드들은 새로운 ZonedDateTime 객체를 반환합니다.
- ZonedDateTime 클래스는 java.time 패키지에서 제공하는 날짜와 시간 관련 클래스 중 하나로, 지역 시간대 정보를 포함한 날짜와 시간을 다루어야 하는 경우에 사용됩니다.

 

이러한 메소드들을 사용하여 ZonedDateTime 객체를 효과적으로 활용할 수 있습니다.

 

With ChatGPT

'JAVA > 포스팅' 카테고리의 다른 글

java.time.Duration 클래스  (0) 2023.11.17
java.time.ZoneId 클래스  (0) 2023.11.17
java.time.LocalDateTime 클래스  (0) 2023.11.17
java.time.LocalTime 클래스  (0) 2023.11.17
java.time.LocalDate 클래스  (0) 2023.11.16