> Java > java지도 시간 > 본문

Java 8의 새로운 날짜 및 시간 클래스에 대한 자세한 소개

黄舟
풀어 주다: 2017-03-31 11:12:26
원래의
1607명이 탐색했습니다.

이 글은 주로 java8에서 새로 추가된 DateTime API의 실제 전투에 관한 것입니다. 새로운 날짜 및 시간 클래스는 오랫동안 기다려온 Java 개발자 커뮤니티의 요청의 결과입니다. Java8 이전에 존재했던 Date 클래스는 항상 비판을 받아 왔으며 많은 사람들이 타사 날짜 라이브러리 joda-time을 사용하기로 선택했습니다. Java8의 날짜 및 시간 API는 jodatime 작성자가 개발했으며 JSR310의 모든 내용을 구현합니다. 이러한 새로운 API는 java.time 패키지에 있습니다.

타사 joda-time 및 date4j는 이미 충분히 강력하므로 Java8에서 이를 다시 구현해야 하는 이유 중 하나는 이러한 타사 라이브러리에 표준과 같은 호환성 문제가 있다는 것입니다. JSF 날짜 변환기는 joda-time API와 호환되지 않습니다. 따라서 사용할 때마다 자체 변환기를 작성해야 합니다. 따라서 JSR310을 사용하면 모든 조항이 java8로 구현됩니다.

새로운 Date 클래스 및 Time 클래스의 디자인 원칙:

불변 클래스

Java8 이전에는 Date 클래스 변경 가능한 클래스입니다. 다중 스레드 환경에서 이를 사용할 때 프로그래머는 Date 객체가 스레드로부터 안전한지 확인해야 합니다. Java 8의 날짜 및 시간 API는 스레드로부터 안전한 불변 클래스를 제공합니다. 프로그래머는 동시성 문제를 고려할 필요가 없습니다.

도메인모델주도디자인 접근 방식

새로운 날짜 및 시간 범주는 "도메인 중심 디자인"을 따릅니다. 개발자는 메서드와 클래스의 기능을 쉽게 이해할 수 있습니다.

다음으로 새로운 날짜 및 시간 API를 살펴보겠습니다.

java.time.LocalDate:

LocalDate는 날짜만 제공하고 시간은 제공하지 않습니다. 정보. 불변이며 스레드로부터 안전합니다.

package org.smarttechie;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/**
* This class demonstrates JAVA 8 data and time API
* @author Siva Prasad Rao Janapati
* */
public class DateTimeDemonstration {
/**
* @param args
*/
public static void main(String[] args) {
   //Create date LocalDate localDate = LocalDate.now();
    System.out.println("The local date is :: " + localDate); 
   //Find the length of the month. That is, how many days are there for this month.
   System.out.println("The number of days available for this month:: " + localDate.lengthOfMonth()); 
   //Know the month name
   System.out.println("What is the month name? :: " + localDate.getMonth().name()); 
   //add 2 days to the today's date.
   System.out.println(localDate.plus(2, ChronoUnit.DAYS)); 
   //substract 2 days from today
   System.out.println(localDate.minus(2, ChronoUnit.DAYS)); 
   //Convert the string to date
   System.out.println(localDate.parse("2017-04-07"));
  }
}
로그인 후 복사

java.time.LocalTime:

LocalTime은 시간만 제공하고 날짜 정보는 제공하지 않으며 스레드로부터 안전합니다.

package org.smarttechie;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
/**
* This class demonstrates JAVA 8 data and time API
* @author Siva Prasad Rao Janapati
* */
public class DateTimeDemonstration {
/**
* @param args
*/
public static void main(String[] args) {
   //Get local time
   LocalTime localTime = LocalTime.now();
   System.out.println(localTime);
  //Get the hour of the day
  System.out.println("The hour of the day:: " + localTime.getHour());
  //add 2 hours to the time.
  System.out.println(localTime.plus(2, ChronoUnit.HOURS));
  //add 6 minutes to the time.
  System.out.println(localTime.plusMinutes(6));
  //substract 2 hours from current time
  System.out.println(localTime.minus(2, ChronoUnit.HOURS));
 }
}
로그인 후 복사

java.time.LocalDateTime:

LocalDateTime은 시간과 날짜 정보를 제공하며, 변경할 수 없는 클래스이며 스레드로부터 안전합니다

package orr.smarttechie;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
/**
* This class demonstrates JAVA 8 data and time API
* @author Siva Prasad Rao Janapati
*
*/
public class DateTimeDemonstration {
/**
* @param args
*/
public static void main(String[] args) {
    //Get LocalDateTime object
    LocalDateTime localDateTime = LocalDateTime.now();
    System.out.println(localDateTime);
    //Find the length of month. That is, how many days are there for this month.
    System.out.println("The number of days available for this month:: " + localDateTime.getMonth().length(true));
    //Know the month name
    System.out.println("What is the month name? :: " + localDateTime.getMonth().name());
    //add 2 days to today's date.
    System.out.println(localDateTime.plus(2, ChronoUnit.DAYS));
    //substract 2 days from today
    System.out.println(localDateTime.minus(2, ChronoUnit.DAYS));
  }
}
로그인 후 복사

java.time.Year:

Year는 연도 정보를 제공하며 불변 클래스이며 스레드로부터 안전합니다.

package orr.smarttechie;
import java.time.Year;
import java.time.temporal.ChronoUnit;
/**
* This class demonstrates JAVA 8 data and time API
* @author Siva Prasad Rao Janapati
*
*/
public class DateTimeDemonstration {
/**
* @param args
*/
public static void main(String[] args) {
   //Get year
   Year year = Year.now();
   System.out.println("Year ::" + year);
   //know the year is leap year or not
   System.out.println("Is year[" +year+"] leap year?"+ year.isLeap());
  }
}
로그인 후 복사

java.time.Duration:

Duration은 주어진 두 날짜 사이에 몇 초와 밀리초가 포함되는지 계산하는 데 사용됩니다. 이는 변경할 수 없는 클래스입니다. safe

java.time.Period:

Period는 주어진 두 날짜 사이의 일, 월 또는 연 수를 계산하는 데 사용되며 변경할 수 없는 클래스입니다. 스레드 안전

package orr.smarttechie;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
/**
* This class demonstrates JAVA 8 data and time API
* @author Siva Prasad Rao Janapati
*
*/
public class DateTimeDemonstration {
/**
* @param args
*/
public static void main(String[] args) {
   LocalDate localDate = LocalDate.now();
   Period period = Period.between(localDate, localDate.plus(2, ChronoUnit.DAYS));
   System.out.println(period.getDays());
  }
}
로그인 후 복사


위 내용은 Java 8의 새로운 날짜 및 시간 클래스에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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