> Java > java지도 시간 > 본문

자바 인스턴트

WBOY
풀어 주다: 2024-08-30 15:49:36
원래의
531명이 탐색했습니다.

Java Instant는 프로그램에서 특정 기능을 수행하기 위해 코드 블록에서 사용할 수 있는 Java의 사전 정의된 메소드 세트입니다. 가장 일반적으로 사용되는 Java Instant 메소드 중 일부는 toString(),parse(), ofEpochMilli(), getEpochSecond(), getNano(), plusMillis(long milliToAdd), plusNanos(long nanosToAdd), plusSeconds(long secondToAdd), minusSeconds입니다. (long secondToSubtract), minusMillis(long millisToSubtract), minusNanos(long nanosToSubtract), CompareTo(Instant otherInstant), isAfter(Instant otherInstant) 및 isBefore(Instant otherInstant). Java의 이 기능은 더 높은 효율성, 놀라운 성능, 재사용성, 최적화된 코드 길이 등으로 알려져 있습니다.

구문

Instant 클래스는 Instant 클래스의 인스턴스를 생성하기 위한 여러 정적 팩토리 메소드를 제공합니다. 다음은 다양한 표준 값을 가진 Instant 클래스의 인스턴스를 얻을 수 있는 정적 메소드입니다.

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

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

Instant instant = Instant.now();
로그인 후 복사

now() 메소드는 시스템 시계에서 현재 순간을 반환합니다. 이 인스턴스는 시작 시간 또는 EPOCH로부터의 총 나노초 수를 나타냅니다. 1970년 1월 1일부터 계산된 시간입니다. 이 순간을 가져오는 방법은 기계 타임스탬프를 나타내는 데 유용하며 다른 방법보다 더 자주 사용됩니다.

Instant instant = Instant.EPOCH;
로그인 후 복사

이 정적 필드는 정확한 EPOCH 시간을 나타내는 Instant 클래스 인스턴스를 반환합니다.

Instant instant = Instant.MAX;
로그인 후 복사

이 정적 필드는 인스턴스의 최대값을 나타내는 Instant 클래스의 인스턴스를 반환합니다.

Instant instant = Instant.MIN;
로그인 후 복사

이 정적 필드는 인스턴스의 최소값을 나타내는 Instant 클래스의 인스턴스를 반환하며 값은 음수입니다.

Java Instant의 방법

여기서 Instant 클래스의 주요 부분이나 사용법이 나옵니다. 다음은 Instant 클래스에 속하는 주요 메소드 목록입니다.

  • toString(): 이 메서드는 Object 클래스에서 재정의되어 ISO-8601 표준을 사용하여 문자열 형식으로 인스턴스를 나타냅니다.

다음은 Instant 클래스의 인스턴스를 가져오는 데 사용할 수 있는 메소드입니다.

  • parse(): 이 메서드는 텍스트 문자열을 인수로 사용하고 전달된 동일한 값을 나타내는 인스턴스 클래스의 인스턴스를 반환합니다. 문자열은 UTC 기준으로 유효한 순간이어야 합니다.
  • ofEpochMilli(): 이 메서드는 긴 입력(밀리초)을 인수로 사용하고 전달된 동일한 값을 나타내는 인스턴스 클래스의 인스턴스를 반환합니다. 이 메소드를 사용하면 java.util.Date 객체를 Instant로 변환할 수 있습니다.

Instant 클래스의 인스턴스는 util.Date(밀리초 정밀도)와 비교하여 나노초 정밀도로 시간을 나타냅니다. 따라서 인스턴트는 해당 값(long보다 큰)을 저장하기 위해 더 많은 저장 공간이 필요합니다. 따라서 인스턴트 클래스는 초의 값을 long 변수에 저장하고 나머지 나노초 값을 int 변수에 저장합니다. 아래 방법을 사용하여 이러한 개별 값에 액세스할 수 있습니다.

  • getEpochSecond(): 이 메서드는 단순히 EPOCH에서 초를 반환합니다.
  • getNano(): 이 메서드는 타임라인 또는 초 시작 부분에서 나노초 수를 반환합니다.

다음은 즉각적인 조작이나 계산에 사용할 수 있는 방법입니다.

  • plusMillis(long millisToAdd): 이 메소드는 인스턴트와 함께 전달된 많은 밀리초를 추가하고 새 인스턴트를 반환합니다.
참고: Instant 클래스는 변경할 수 없는 클래스이므로 모든 조작 작업에 대해 새 인스턴스를 반환합니다.
  • plusNanos(long nanosToAdd): 이전 것과 유사하지만 나노초가 추가되었습니다.
  • plusSeconds(long secondToAdd): 초를 추가합니다.

빼기 또는 빼기 연산에도 비슷한 방법이 있습니다. 이 메서드는 인스턴트에서 전달된 초 수를 빼고 새 인스턴트를 반환합니다.

  • minusSeconds(긴 초를 빼려면)
  • minusMillis(long millisToSubtract)
  • minusNanos(long nanosToSubtract)

다음은 두 순간을 비교하는 데 사용할 수 있는 방법입니다.

  • compareTo(Instant otherInstant): This method will compare the one instant with the passed one. Returns the integer value negative if it is less and positive if it is greater.
  • isAfter(Instant otherInstant): This method checks if the passed instant is after the current instant. Returns true or false.
  • isBefore(Instant otherInstant): Similar to the previous one, checks if the passed instant is before the current instant. Returns true or false.

Examples to Implement Java Instant

Below are the examples of implementing java instant:

1. toString()

Code:

import java.time.Instant;
public class app {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println( instant.toString() );
}
}
로그인 후 복사

Output:

자바 인스턴트

The output will be the time of the system running the code.

2. getEpochSecond()

Code:

import java.time.Instant;
public class app {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println( instant.getEpochSecond() );
}
}
로그인 후 복사

Output:

자바 인스턴트

3. getNano()

Code:

import java.time.Instant;
public class app {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println( instant.getNano() );
}
}
로그인 후 복사

Output:

자바 인스턴트

4. plusSeconds()

Code:

import java.time.Instant;
public class app {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println( instant );
instant = instant.plusSeconds( 3600 );
System.out.println( instant );
}
}
로그인 후 복사

Output:

자바 인스턴트

We have added exactly 3600 seconds, i.e. 1 hour, to the current instant, as it can be seen in the output that time is increased by 1 hour.

5. compareTo()

Code:

import java.time.Instant;
public class app {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println( instant );
Instant instant2 = instant.plusSeconds( 3600 );
System.out.println( instant.compareTo( instant2 ) );
}
}
로그인 후 복사

Output:

자바 인스턴트

Here, we are comparing two instants, current with the instant having added 1 more hour. As the current instance is less than instance2, the output is negative.

Conclusion

So, we have seen the Instant class introduced from Java 8. This class represents the seconds from the start of the timeline with nanoseconds precision. This class is useful to generate the timestamp, which will represent the system time. We have seen different types of instants which we can get and different methods useful for calculations, creating a new instantly, comparing instants, getting seconds and nanoseconds differently, etc. Instant class is immutable and provides thread safety as compared to the old Date object. The Instant class is much more powerful than the old time-date API.

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

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!