찾다

자바 기간

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 응용 프로그램에 어떻게 도움이됩니까?플랫폼 독립성은 기업 수준의 Java 응용 프로그램에 어떻게 도움이됩니까?May 03, 2025 am 12:23 AM

Java는 플랫폼 독립성으로 인해 엔터프라이즈 수준의 응용 프로그램에서 널리 사용됩니다. 1) 플랫폼 독립성은 JVM (Java Virtual Machine)을 통해 구현되므로 JAVA를 지원하는 모든 플랫폼에서 코드가 실행될 수 있습니다. 2) 크로스 플랫폼 배포 및 개발 프로세스를 단순화하여 유연성과 확장 성을 더 많이 제공합니다. 3) 그러나 성능 차이 및 타사 라이브러리 호환성에주의를 기울이고 순수한 Java 코드 사용 및 크로스 플랫폼 테스트와 같은 모범 사례를 채택해야합니다.

Java는 플랫폼 독립성을 고려하여 IoT (Internet of Things) 장치의 개발에서 어떤 역할을합니까?Java는 플랫폼 독립성을 고려하여 IoT (Internet of Things) 장치의 개발에서 어떤 역할을합니까?May 03, 2025 am 12:22 AM

javaplaysaSignificantroleiniotduetoitsplatformincentence.1) itallowscodetobewrittenonceandevices.2) java'secosystemprovidesusefullibrariesforiot.3) itssecurityfeaturesenhanceiotiotsystemsafety.hormormory.hormory.hustupletety.houghmormory

Java에서 플랫폼 별 문제를 발견 한 시나리오와 해결 방법을 설명하십시오.Java에서 플랫폼 별 문제를 발견 한 시나리오와 해결 방법을 설명하십시오.May 03, 2025 am 12:21 AM

thejava.nio.filepackage.1) withsystem.getProperty ( "user.dir") andtherelativeatthereplattHefilePsiple.2) thepathtopilebtoafne 컨버터링 주제

개발자를위한 Java의 플랫폼 독립성의 이점은 무엇입니까?개발자를위한 Java의 플랫폼 독립성의 이점은 무엇입니까?May 03, 2025 am 12:15 AM

Java'SplatformIndenceSnictIficantIficantBecauseItAllowsDeveloperstowRiteCodeOnceAntOnitonAnyplatformwithajvm.이 "WriteOnce, Runanywhere"(WORA) 접근자 : 1) 교차 플랫폼 컴퓨팅 성, DeploymentAcrossDifferentoSwithoutissswithoutissuesswithoutissuesswithoutswithoutisssues를 활성화합니다

다른 서버에서 실행 해야하는 웹 애플리케이션에 Java를 사용하는 장점은 무엇입니까?다른 서버에서 실행 해야하는 웹 애플리케이션에 Java를 사용하는 장점은 무엇입니까?May 03, 2025 am 12:13 AM

Java는 크로스 서버 웹 응용 프로그램을 개발하는 데 적합합니다. 1) Java의 "Write Once, Run Everywhere"철학은 JVM을 지원하는 모든 플랫폼에서 코드를 실행합니다. 2) Java는 Spring 및 Hibernate와 같은 도구를 포함하여 개발 프로세스를 단순화하는 풍부한 생태계를 가지고 있습니다. 3) Java는 성능 및 보안에서 훌륭하게 성능을 발휘하여 효율적인 메모리 관리 및 강력한 보안 보증을 제공합니다.

JVM은 Java의 'Write Once, Run Aloneeringly'(Wora) 기능에 어떻게 기여합니까?JVM은 Java의 'Write Once, Run Aloneeringly'(Wora) 기능에 어떻게 기여합니까?May 02, 2025 am 12:25 AM

JVM은 바이트 코드 해석, 플랫폼 독립 API 및 동적 클래스 로딩을 통해 Java의 Wora 기능을 구현합니다. 1. 바이트 코드는 크로스 플랫폼 작동을 보장하기 위해 기계 코드로 해석됩니다. 2. 표준 API 추상 운영 체제 차이; 3. 클래스는 런타임에 동적으로로드되어 일관성을 보장합니다.

최신 버전의 Java는 플랫폼 별 문제를 어떻게 해결합니까?최신 버전의 Java는 플랫폼 별 문제를 어떻게 해결합니까?May 02, 2025 am 12:18 AM

JAVA의 최신 버전은 JVM 최적화, 표준 라이브러리 개선 및 타사 라이브러리 지원을 통해 플랫폼 별 문제를 효과적으로 해결합니다. 1) Java11의 ZGC와 같은 JVM 최적화는 가비지 수집 성능을 향상시킵니다. 2) Java9의 모듈 시스템과 같은 표준 라이브러리 개선은 플랫폼 관련 문제를 줄입니다. 3) 타사 라이브러리는 OpenCV와 같은 플랫폼 최적화 버전을 제공합니다.

JVM이 수행 한 바이트 코드 검증 프로세스를 설명하십시오.JVM이 수행 한 바이트 코드 검증 프로세스를 설명하십시오.May 02, 2025 am 12:18 AM

JVM의 바이트 코드 검증 프로세스에는 네 가지 주요 단계가 포함됩니다. 1) 클래스 파일 형식이 사양을 준수하는지 확인, 2) 바이트 코드 지침의 유효성과 정확성을 확인하고 3) 유형 안전을 보장하기 위해 데이터 흐름 분석을 수행하고 4) 검증의 철저한 성능 균형을 유지합니다. 이러한 단계를 통해 JVM은 안전하고 올바른 바이트 코드 만 실행되도록하여 프로그램의 무결성과 보안을 보호합니다.

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 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.