search
HomeJavajavaTutorialDetailed introduction to the new Date and Time classes in Java 8

This article is mainly about the actual combat of the new Date and Time API in java8. The new Date and Time classes are the result of long-awaited requests from the Java developer community. The Date class that existed before Java8 has always been criticized, and many people choose to use the third-party date library joda-time. The date and time API in Java8 was developed by the author of jodatime and implements all the contents of JSR310. These new APIs are under the package java.time.

Since the third-party joda-time and date4j are already powerful enough, why does Java8 need to re-implement them? Part of the reason is that these third-party libraries have compatibility issues, such as the standard JSF date The converter is incompatible with the joda-time API. Every time you use it, you need to write your own converter. Therefore, a standardized API is necessary. With JSR310, all its provisions are implemented in Java8.

Design principles behind the new Date class and Time class:

Immutable class

Before java8, the Date class was It is a mutable class. When we use it in a multi-threaded environment, programmers should confirm that the Date object is thread-safe. Java 8's Date and Time APIs provide thread-safe immutable classes. Programmers do not need to consider concurrency issues.

DomainModelDrivenDesign Approach

The new date and time categories follow "Domain Driven Design". It is easy for developers to understand the functionality of methods and classes.

Next let's take a look at the new Date and Time API:

java.time.LocalDate:

LocalDate only provides date but not time information. It is immutable and thread-safe.

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 only provides time but not date information. It is an immutable class and thread-safe.

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 provides time and date information, it is an immutable class and thread-safe

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 provides year information, it is an immutable class and thread-safe.

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 is used to calculate how many seconds and milliseconds are included between two given dates. It is an immutable class And thread-safe

java.time.Period:

Period is used to calculate how many days, months or years there are between two given dates. , it is an immutable class and thread-safe

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());
  }
}


The above is the detailed content of Detailed introduction to the new Date and Time classes in Java 8. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor