>  기사  >  Java  >  자바 기간

자바 기간

王林
王林원래의
2024-08-30 15:52:12954검색

자바의 Duration은 시간을 초와 나노초 단위로 측정하는 데 사용되는 클래스입니다. Java의 기간 클래스 패키지는 java.time.Duration입니다. Duration 클래스 객체는 기간을 지정하거나 두 시간 간의 차이를 결정하는 데 사용됩니다. Duration 객체는 불변이고 스레드로부터 안전합니다. Duration 객체는 불변이므로 일단 생성되면 해당 값을 변경할 수 없습니다. 그러나 다른 Duration 개체를 기반으로 새 Duration 개체를 만들 수 있습니다. Duration 클래스는 객체 클래스(객체는 Java의 모든 클래스의 슈퍼클래스이므로)를 상속하고 Comparable 인터페이스를 구현합니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

Java의 Duration 클래스 선언 구문은 다음과 같습니다.

public final class Duration extends Object implements Comparable < Duration >,
TemporalAmount, Serializable
{
//
variables and method of the class Duration}

기간 목록

아래에는 Duration 클래스 메소드 목록이 예제 코드와 함께 설명되어 있습니다. 유사한 메서드에 대해 예제 코드를 추가로 사용할 수 있습니다(각 메서드 예제 코드는 제공되지 않음):

  • 기간 abs(): 이 메소드는 양수 길이의 기간 복사본을 반환합니다.
  • long get(TemporalUnit 단위): 요청한 단위의 값을 반환합니다.
  • 정적 기간 사이(Temporal startInclusive, Temporal endExclusive): 두 시간 개체 사이의 기간인 기간 개체를 반환합니다.

예시 #1

아래의 샘플 자바 코드를 통해 위의 메소드를 이해했습니다.

코드:

package p1;
import java.time.Duration;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.MAX,LocalTime.MIN);
System.out.println(d.get(ChronoUnit.SECONDS));
Duration absd = d.abs();
System.out.println(absd.get(ChronoUnit.SECONDS));
}
}

출력:

자바 기간

  • Temporal addTo(Temporal temporary): 시간 객체와 이 기간 객체를 더한 기간 객체를 반환합니다.
  • Duration Divider(long divisor): 이 기간을 제수로 나눈 기간 객체를 반환합니다.

예시 #2

아래 샘플 자바 코드를 통해 위의 메소드를 이해합니다.

코드:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.MAX,LocalTime.MIN);
LocalDateTime date = LocalDateTime.now();
System.out.println(date);
date = (LocalDateTime)d.addTo(date);
System.out.println(date);
Duration d1 = d.dividedBy(4);
System.out.println(d1);
System.out.println(d.getSeconds());
System.out.println(d1.getSeconds());
}
}

출력:

자바 기간

  • int CompareTo(Duration otherDuration): 이 기간과 지정된 기간을 비교합니다.
  • boolean equals(Object otherDuration): 지정된 Duration으로 이 기간을 확인하고 Boolean을 반환합니다.
  • boolean isNegative(): 이 기간이 음수이면 True를 반환합니다.
  • boolean isZero(): 이 기간 길이가 0이면 True를 반환합니다.

예시 #3

아래 샘플 자바 코드를 통해 위의 메소드를 이해합니다.

코드:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX);
Duration d1 = Duration.between(LocalTime.NOON,LocalTime.MIN);
System.out.println(d1.getSeconds());
System.out.println(d.compareTo(d1));
System.out.println(d1.compareTo(d1));
System.out.println(d1.compareTo(d));
System.out.println(d1.equals(d));
System.out.println(d1.isNegative());
System.out.println(d1.isZero());
}
}

출력:

자바 기간

  • 정적 지속 시간(TemporalAmount amount): 시간적 양에서 지속 시간의 인스턴스를 얻습니다.

예시 #4

아래 샘플 자바 코드를 통해 위의 방법을 이해합니다.

코드:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.from(ChronoUnit.DAYS.getDuration());
System.out.println(d.toMinutes());
}
}

출력:

자바 기간

  • int getNano(): 나노초 단위로 기간을 반환합니다.
  • long getSeconds(): 기간을 초 단위로 반환합니다.
  • 목록<임시단위> getUnits(): 이 기간에 지원되는 단위 집합을 반환합니다.
  • int hashCode(): 이 기간 동안 해시 코드를 반환합니다.

예시 #5

아래 샘플 자바 코드를 통해 위의 방법을 이해합니다.

코드:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.between(LocalTime.NOON,LocalTime.MAX);
System.out.println(d.getUnits());
System.out.println(d.toMinutes());
System.out.println(d.getSeconds());
System.out.println(d.getNano());
System.out.println(d.getClass());
}
}

출력:

자바 기간

  • Duration minus(Duration duration):- Returns object which results from this duration subtracted with the specified duration.
  • Duration minus(long amountToSubtract, TemporalUnit unit): Returns object resulting from this duration subtracted with the specified duration.
  • Duration minusDays(long daysToSubtract): Returns object which results from this duration subtracted with the specified duration in standard 24-hour days.
  • Duration minusHours(long hoursToSubtract): Returns object resulting from this duration subtracted with the specified duration in hours.
  • Duration minusMillis(long millisToSubtract): Returns object resulting from this duration subtracted with the specified duration in milliseconds.
  • Duration minusMinutes(long minutesToSubtract): Returns object resulting from this duration subtracted with the specified duration in minutes.
  • Duration minusNanos(long nanosToSubtract): Returns object resulting from this duration subtracted with the specified duration in nanoseconds.
  • Duration minusSeconds(long secondsToSubtract): Returns object resulting from this duration subtracted with the specified duration in seconds.
  • Duration multipliedBy(long multiplicand): Returns object resulting from this duration multiplied by the scalar.
  • Duration negated() – Returns object which results from this duration with the length negated.
  • static duration of(long amount, TemporalUnit unit): Returns Duration object representing an amount in the specified unit.
  • static Duration ofDays(long days): Returns Duration object of standard 24-hour days.
  • static Duration ofHours(long hours): Returns Duration object of the hour.
  • static Duration ofMillis(long millis): Returns Duration object of milliseconds.
  • static Duration ofMinutes(long minutes): Returns Duration object of minutes.
  • static Duration ofNanos(long nanos): Returns Duration object of nanoseconds.
  • static Duration ofSeconds(long seconds): Returns Duration object of seconds.
  • static Duration ofSeconds(long seconds, long nanoAdjustment): Returns Duration object of seconds and nanoseconds adjustment.

Example #6

We understand the above methods with the below sample java code:

Code:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.getSeconds());
Duration d1 = d.minusDays(3);
System.out.println(d1.getSeconds());
d = Duration.ofHours(6);
System.out.println(d.getSeconds());
d1 = d.minusHours(2);
System.out.println(d1.getSeconds());
}
}

Output:

자바 기간

  • static Duration parse(CharSequence text): Return duration object from a text, for example, PnDTnHnMn.nS.
  • Duration plus(Duration duration): Return the duration object of this duration with added the specified duration.
  • Duration plus(long amountToAdd, TemporalUnit unit): Return the duration object of this duration with add the specified duration.
  • Duration plusDays(long daysToAdd): Return the duration object of this duration with add the specified duration in 24-hour days.
  • Duration plusHours(long hoursToAdd): Return the duration object of this duration with add the specified duration in hours.
  • Duration plusMillis(long millisToAdd): Return the duration object of this duration with add the specified duration in milliseconds.
  • Duration plusMinutes(long minutesToAdd): Return the duration object of this duration with the add specified duration in minutes.
  • Duration plusNanos(long nanosToAdd): Return the duration object of this duration with add the specified duration in nanoseconds.
  • Duration plusSeconds(long secondsToAdd): Return the duration object of this duration with the specified duration in seconds.

Example #7

We understand the above methods with the below sample java code:

Code:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.getSeconds());
Duration d1 = d.plusDays(2);
System.out.println(d1.getSeconds());
d = Duration.ofHours(6);
System.out.println(d.getSeconds());
d1 = d.plusHours(2);
System.out.println(d1.getSeconds());
}
}

Output:

자바 기간

  • Temporal subtractFrom(Temporal temporal): Return Subtraction of this duration from the temporal object.
  • long toDays(): Return the number of days in this duration.
  • long toHours(): Return the number of hours in this duration.
  • long toMillis(): Return the number of milliseconds in this duration.
  • long toMinutes(): return the number of minutes in this duration.
  • long toNanos(): return the number of nanoseconds in this duration.
  • String toString(): Return this duration in string representation, such as PT8H6M12.345S.

Example #8

We understand the above methods with the below sample java code:

Code:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.toHours());
Duration d1 =Duration.ofHours(24) ;
System.out.println(d1.toDays());
}
}

Output:

자바 기간

  • Duration withNanos(int nanoOfSecond): Returns duration object with the specified nanoofsecond.
  • Duration withSeconds(long seconds): Returns duration object of this duration with the seconds of the specified amount.

Example #9

We understand the above methods with the below sample java code:

Code:

package p1;
import java.time.Duration;
import java.time.*;
import java.time.temporal.ChronoUnit;
public class DurationClassDemo {
public static void main(String[] args) {
Duration d = Duration.ofDays(6);
System.out.println(d.toString());
d = d.withSeconds(3000);
System.out.println(d.toString());
}
}

Output:

자바 기간

Conclusion

The Duration class is one of the built-in class in java, which is used to measure time in seconds and nanoseconds and add, subtract, and convert the duration, or, in simple words, the duration class allows performance operation on time or day duration. The duration class is available in java.time.Duration package of java.

위 내용은 자바 기간의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 LocalDateTime다음 기사:자바 LocalDateTime