찾다

자바 기간

Aug 30, 2024 pm 03:52 PM
java

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

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

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

구문

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

public final class Duration extends Object implements Comparable ,
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으로 문의하세요.
고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?Mar 17, 2025 pm 05:46 PM

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?적절한 버전 및 종속성 관리로 Custom Java 라이브러리 (JAR Files)를 작성하고 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:45 PM

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?Mar 17, 2025 pm 05:44 PM

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?Mar 17, 2025 pm 05:43 PM

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?Mar 17, 2025 pm 05:35 PM

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

분산 컴퓨팅에 Java의 RMI (원격 메소드 호출)를 어떻게 사용할 수 있습니까?분산 컴퓨팅에 Java의 RMI (원격 메소드 호출)를 어떻게 사용할 수 있습니까?Mar 11, 2025 pm 05:53 PM

이 기사에서는 분산 응용 프로그램을 구축하기위한 Java의 원격 메소드 호출 (RMI)에 대해 설명합니다. 인터페이스 정의, 구현, 레지스트리 설정 및 클라이언트 측 호출을 자세히 설명하여 네트워크 문제 및 보안과 같은 문제를 해결합니다.

네트워크 통신에 Java의 Sockets API를 어떻게 사용합니까?네트워크 통신에 Java의 Sockets API를 어떻게 사용합니까?Mar 11, 2025 pm 05:53 PM

이 기사는 네트워크 통신을위한 Java의 소켓 API, 클라이언트 서버 설정, 데이터 처리 및 리소스 관리, 오류 처리 및 보안과 같은 중요한 고려 사항에 대해 자세히 설명합니다. 또한 성능 최적화 기술, i

Java에서 사용자 정의 네트워킹 프로토콜을 어떻게 만들 수 있습니까?Java에서 사용자 정의 네트워킹 프로토콜을 어떻게 만들 수 있습니까?Mar 11, 2025 pm 05:52 PM

이 기사에서는 맞춤형 Java 네트워킹 프로토콜을 작성합니다. 프로토콜 정의 (데이터 구조, 프레임, 오류 처리, 버전화), 구현 (소켓 사용), 데이터 직렬화 및 모범 사례 (효율성, 보안, Mainta를 포함합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경