java에서 시간의 간격 및 기간을 나타내는 Duration, Period 클래스에 대해서 알아보자.
두 날짜 사이의 간격을 년,월,일 단위로 나타낸다.
public class Period {
private final int years;
private final int months;
private final int days;
}
package time;
import java.time.LocalDate;
import java.time.Period;
public class PeriodMain {
public static void main(String[] args) {
//생성
Period period = Period.ofDays(10);
System.out.println("period = " + period);
//계산에 사용
LocalDate currentDate = LocalDate.of(2030, 1, 1);
LocalDate plusDate = currentDate.plus(period);
System.out.println("현재 날짜: " + currentDate);
System.out.println("더한 날짜: " + plusDate);
//기간 차이
LocalDate startDate = LocalDate.of(2023, 1, 1);
LocalDate endDate = LocalDate.of(2023, 4, 2);
Period between = Period.between(startDate, endDate);
System.out.println("기간: " + between.getMonths() + "개월 " + between.getDays() + "일");
}
}
period = P10D
현재 날짜: 2030-01-01
더한 날짜: 2030-01-11
기간: 3개월 1일
두 시간 사이의 간격을 시,분,초 단위로 나타낸다.
public class Duration {
private final long seconds;
private final int nanos;
}
내부에서 초를 기반으로 시,분,초를 계산해서 사용한다.
package time;
import java.time.Duration;
import java.time.LocalTime;
public class DurationMain {
public static void main(String[] args) {
//생성
Duration duration = Duration.ofMinutes(30);
System.out.println("duration = " + duration);
LocalTime lt = LocalTime.of(1, 0);
System.out.println("기준 시간 = " + lt);
//계산에 사용
LocalTime plusTime = lt.plus(duration);
System.out.println("더한 시간 = " + plusTime);
//시간 차이
LocalTime start = LocalTime.of(9, 0);
LocalTime end = LocalTime.of(10, 0);
Duration between = Duration.between(start, end);
System.out.println("차이: " + between.getSeconds() + "초");
System.out.println("근무 시간: " + between.toHours() + "시간 " +
between.toMinutesPart() + "분");
}
}
duration = PT30M
기준 시간 = 01:00
더한 시간 = 01:30
차이: 3600초
근무 시간: 1시간 0분
java에서 Thread를 생성하는 방법 (1) | 2025.05.26 |
---|---|
Instant (1) | 2025.05.23 |
OffsetDateTime (0) | 2025.05.23 |
ZonedDateTime (1) | 2025.05.22 |
Context Switching이란? (0) | 2025.05.16 |
댓글 영역