>  기사  >  Java  >  자바 현지 시간

자바 현지 시간

WBOY
WBOY원래의
2024-08-30 15:49:48635검색

Java LocalTime은 날짜 및 시간과 관련된 여러 작업에 사용할 수 있는 내장 기능 패키지 중 하나입니다. LocalTime 관련 작업의 경우 Java에는 Java Time이라는 특정 API(응용 프로그램 인터페이스)가 있으며, 이는 모든 날짜 및 시간 관련 기능에 적용할 수 있는 여러 메서드를 보유합니다. LocalTime 클래스에서 일반적으로 사용되는 메소드로는 get(), CompareTo(), equals, atDate(), of(), now(), plusHours(), minusHours() 등이 있으며 시간, 분, 초를 사용합니다. 사전 정의된 객체.

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

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

Java 8의 LocalTime 클래스를 이해했으니 이제 Syntax를 배워보겠습니다.

구문:

공용 최종 클래스 LocalTime은 Object를 확장하여 Comparable을 구현합니다.

위 구문은 클래스를 초기화하는 표준 방법입니다. 앞서 언급했듯이 LocalTime 클래스는 Object 클래스를 확장하고 이에 상응하는 인터페이스를 구현합니다.

Java LocalTime 메서드

이제 LocalTime 클래스에서 제공되는 메서드를 살펴보겠습니다.

public LocalDateTime atDate(LocalDate date)

1. atDate(): LocalDateTime을 생성하려면 이 시간을 날짜와 결합합니다. 결합할 날짜를 매개 변수로 사용하며 null을 허용하지 않습니다. 여기에서는 가능한 모든 날짜 및 시간 조합이 유효합니다.

public int compareTo(LocalTime other)

2. CompareTo(): 이 시간을 다른 통과 시간과 간단히 비교합니다. 비교할 다른 시간을 매개변수로 사용합니다. 비교 값을 반환합니다. 크면 양수, 작으면 음수입니다. 다른 값이 전달되지 않거나 전달에 실패하는 경우 NullPointerException이 발생합니다.

public int get(TemporalField field)

3. get(): 이 시점의 값을 정수로 가져옵니다. 매개변수로 가져올 필드를 사용하며 Null을 허용하지 않습니다. 그리고 필드의 값을 반환합니다. 반환 값은 항상 범위 내에 있습니다. 어떤 이유로든 값을 반환하지 못하는 경우 예외가 발생합니다.

4. 예외: 값이 범위를 벗어나거나 값을 얻을 수 없는 경우 DateTimeException이 발생합니다. 그리고 숫자 오버플로가 발생할 경우 ArithmeticException이 발생합니다.

public boolean equals(Object obj)

5. 같음: 이 시간과 다른 시간의 간단한 비교입니다. 확인할 객체를 파라미터로 인자로 받으며, false일 경우 null을 반환한다. 클래스 객체의 같음을 재정의합니다. 여기서는 LocalTime 유형의 객체만 비교됩니다. 다른 유형의 경우 false를 반환합니다.

public static LocalTime now()

6. now(): 기본 시간대에서 now()는 시스템에서 현재 시간을 가져옵니다. Never Null은 항상 현재 시스템 시간을 반환합니다.

public static LocalTime now(ZoneId zone)

7. now(ZoneId zone): 위와 비슷하지만 시간대가 지정되어 있습니다. 영역 ID를 매개변수로 사용하며 null을 허용하지 않습니다. 전달된 시간대의 현재 시간을 반환합니다.

public static LocalTime of(int hour, int minute, int second, int nanoOfSecond):

8. of(): LocalTime의 인스턴스를 얻습니다. 4개의 매개변수를 시, 분, 초, 나노초로 사용하고 현지 시간을 반환하며 절대 null이 아닙니다. 값이 범위를 벗어나는 경우 DateTimeException이 발생합니다.

public LocalTime minusHours(long hoursToSubtract):

9. minusHours(): 이 LocalTime의 복사본은 시간 수를 뺀 값으로 반환됩니다. 매개변수로 hourToSubtract를 사용합니다. 부정적이어서는 안 됩니다. 그리고 시간 수를 뺀 이 LocalTime을 반환합니다. 여기의 인스턴스는 변경할 수 없으며 메서드 호출의 영향을 받지 않습니다.

public LocalTime plusHours(long hoursToAdd):

10. plusHours(): 위에서 언급한 방법과 정반대입니다. 지정된 시간 수를 추가하여 이 LocalTime의 복사본을 반환합니다. 위와 유사하게 불변이고 영향을 받지 않습니다.

Java LocalTime 구현 예시

이제 위의 방법을 이해했으므로 이러한 방법을 예시로 보여드리겠습니다.

예시 #1

코드:

public class localtime {
public static void main(String[] args) {
LocalTime time_now = LocalTime.now();
System.out.println(time_now);
}
}

코드 해석: 예 1에서는 단순히 LocalTime 클래스의 now() 메서드를 구현했습니다. 클래스를 만든 다음 메인 클래스, 메서드 호출 및 간단한 출력 문을 만듭니다. 실행 시 현재 시스템 시간이 반환됩니다. 출력은 시, 분, 초, 미니초 형식으로 표시됩니다. 출력은 아래 스크린샷을 참고하세요.

출력:

자바 현지 시간

예시 #2

코드:

import java.time.LocalTime;
public class localtime {
public static void main(String[] args) {
LocalTime time_1 = LocalTime.of(10,43,12);
System.out.println(time_1);
LocalTime time_2=time_1.minusHours(3);
LocalTime time_3=time_2.minusMinutes(41);
System.out.println(time_3);
}
}

Code Interpretation: Here, we have demonstrated two methods, minusHours() and minusMinutes(). After creating our class and main class, we called the () method with parameters and printed the next line’s output. Later, we created two objects with two methods, respectively, for hours and for minutes. So, out of the given time in of() method, the number of hours to be subtracted will be 2, and minutes will be 41. With that in mind, our output should be 10-3 hours, which is 7 hours and 43-41 minutes, which will be 2 minutes. So, the final output must be “07:02:12”. For sample output, refer to the below attached screenshot.

Output:

자바 현지 시간

Example #3

Code:

import java.time.*;
public class localtime {
public static void main(String[] args) {
LocalTime time1 = LocalTime.parse("13:08:00");
LocalTime time_now = LocalTime.now();
System.out.println("LocalTime1: " + time1);
System.out.println("LocalTime2: " + time_now);
boolean eq_value = time1.equals(time_now);
System.out.println("Both times are equal: "  + eq_value);
}
}

Code Interpretation: In our 3rd example, we have implemented the equals method. Other than the creation of class and the main class, we have two objects with assigned values. At first, we have passed a specific time, and for the second, we have fetched the current time of the system with the now() method. Later, we have printed these two values and then a boolean comparison. Using the equals() method, we have compared the two times and passed the output to the output print statement. The equals method’s output will be either true or false; based on the values passed here, the output here must be false. Refer below the screenshot for output.

Output:

자바 현지 시간

Conclusion

Java 8’s Date Time update comes with many features, and LocalTime is one of them, which does not store any value but is a better representation of the date and time. We understood the methods with description and followed by three example samples. LocalTime class of java provides a wide range of methods, more than mentioned and can be used as per requirement.

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

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