Core Java

Java 8 LocalDateTime Example

Hello readers, Java provides a new Date and Time API in Java8. This tutorial demonstrates how to use the LocalDateTime class with few important methods defined in this class.
 
 
 
 
 
 
 
 

1. Introduction

The java.time.LocalDateTime is a new class introduced on the Java8 Date and Time API. This immutable class is in java.time package and it represents both date and time information without the time-zone information such as 2017-07-12T10:35:55. This class does not store and represent the time-zone. Instead, it is a description of date-time which can be viewed as year-month-day-hour-minute-second.

In this tutorial, developers will learn the different ways to create an instance of LocalDateTime class in Java8. For e.g. by using the static factory method or by combining the LocalDate and LocalTime instances together, which are subsequently used to denote date without time and time without the date in Java8. As their name suggests they are local, so they don’t contain the time-zone information. They are always bound to the local time-zone i.e. the time-zone of the machine on which the Java program is running. The class which contains the date, time and time-zone information is known as ZonedDateTime in Java8.

Many Java programmer thinks that since LocalDateTime contains both date and time information it is equivalent to java.util.Date class, but this is not true. The equivalent class of java.util.Date in the new date and time API is not the LocalDateTime but the java.time.Instance because the date is nothing but a millisecond value from Epoch.

The easiest way to create an instance of the LocalDateTime class is by using the factory method (i.e. of()). This accepts year, month, day, hour, minute, and second to create an instance of this class. A shortcut to create an instance of this class is by using the atDate() and atTime() methods of the LocalDate and LocalTime classes.

1.1 Declaration of Java LocalDateTime Class

Let’s see the declaration of the java.time.LocalDateTime class.

public final class LocalDateTime extends Object implements Temporal, TemporalAdjuster, ChronoLocalDateTime, Serializable

1.2 Methods of Java LocalDateTime Class

MethodDescription
String format(DateTimeFormatter formatter)It is used to format this date-time using the specified formatter.
int get(TemporalField field)It is used to get the value of the specified field from this date-time as an int.
LocalDateTime minusDays(long days)It is used to return a copy of this LocalDateTime with the specified number of days subtracted.
static LocalDateTime now()It is used to obtain the current date-time from the system clock in the default time-zone.
static LocalDateTime of(LocalDate date, LocalTime time)It is used to obtain an instance of LocalDateTime from a date and time.
LocalDateTime plusDays(long days)It is used to return a copy of this LocalDateTime with the specified number of days added.
boolean equals(Object obj)It is used to check if this date-time is equal to another date-time.

Now, open up the Eclipse Ide and I will explain further about the new Date and Time API.

2. Java8 LocalDateTime Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Java8LocalDateTime</groupId>
	<artifactId>Java8LocalDateTime</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to demonstrate the new Date and Time API in the Java8 programming. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: LocalDateTimeDemo. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (LocalDateTimeDemo.java)
Fig. 8: Java Class (LocalDateTimeDemo.java)

3.1.1 Example on LocalDateTime

Here is the complete Java program to demonstrate the use of LocalDateTime class in the Java8 programming. Let’s see the simple code snippet that follows this implementation.

LocalDateTimeDemo.java

package com.jcg.java;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeDemo {

	public static void main(String[] args) {

		/**** LocalDate is Date Without Time in Java8 ****/
		/**** LocalTime is Time Without Date in Java8 ****/
		/**** LocalDateTime is both Date and Time e.g. LocalDate + LocalTime but without TimeZone information ****/

		/**** EXAMPLE #1 ****/
		/**** LocalDateTime.now() creates a LocalDateTieme object with Current Date and Time ****/
		LocalDateTime rightNow = LocalDateTime.now();
		System.out.println("Current DateTime?= " + rightNow + "\n");

		/**** Formatting the Date using ISO_LOCAL_DATE ****/
		String isoDate = rightNow.format(DateTimeFormatter.ISO_LOCAL_DATE);
		System.out.println("ISO Formatted Date?= " + isoDate + "\n");

		/**** Formatting the Date using PATTERN ****/
		String pattern = "dd-MMM-yyyy HH:mm:ss";
		String patternDate = rightNow.format(DateTimeFormatter.ofPattern(pattern));
		System.out.println("Pattern Formatted DateTime?= " + patternDate + "\n");

		/**** EXAMPLE #2 ****/
		/**** LocalDateTime.of() method is a factory method to create LocalDateTiem with Specific Date and Time ****/
		LocalDateTime sDateTime = LocalDateTime.of(2017, Month.DECEMBER, 22, 21, 30, 40); 
		System.out.println("Some DateTime?= " + sDateTime + "\n");

		/**** EXAMPLE #3 ****/
		/**** Developers can also create LocalDateTime object by combining LocalDate and LocalTime ****/
		LocalDate currentDate = LocalDate.now(); 
		LocalTime currentTime = LocalTime.now(); 
		LocalDateTime fromDateAndTime = LocalDateTime.of(currentDate, currentTime); 
		System.out.println("LocalDateTime created by combining 'LocalDate' and 'LocalTime'?= " + fromDateAndTime + "\n");

		/**** EXAMPLE #4 ****/
		/**** Developers can also retrieve LocalDate and LocalTime from LocalDateTime ****/
		LocalDate retrievedDate = fromDateAndTime.toLocalDate(); 
		LocalTime retrievedTime = fromDateAndTime.toLocalTime(); 
		System.out.println("Retrieved LocalDate?= " + retrievedDate + ", Retrieved LocalTime?= " + retrievedTime);		
	}
}

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The application shows the following logs as output.

# Logs for 'LocalDateTimeDemo' #
================================
Current DateTime?= 2018-01-21T12:01:34.481

ISO Formatted Date?= 2018-01-21

Pattern Formatted DateTime?= 21-Jan-2018 12:01:34

Some DateTime?= 2017-12-22T21:30:40

LocalDateTime created by combining 'LocalDate' and 'LocalTime'?= 2018-01-21T12:01:34.519

Retrieved LocalDate?= 2018-01-21, Retrieved LocalTime?= 12:01:34.519

That’s all for this post. Happy Learning!

6. Conclusion

That’s all for Java8 Date and Time API example. Developers can use it to represent the date-time without a time-zone in the ISO-8601 calendar system. I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Date and Time API in Java8.

Download
You can download the full source code of this example here: Java8LocalDateTime

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button