Java 8 Date and Time Classes with Examples

The Date-Time API provides two classes that deal exclusively with time information.
  1. LocalTime
  2. LocalDateTime
Let's discuss each class with examples. Examples of this guide are available on Github.

1. LocalTime

The LocalTime class is similar to the other classes whose names are prefixed with Local, but deals in time only. This class is useful for representing human-based time of day, such as movie times, or the opening and closing times of the local library.

1.1 LocalTime Class Examples

Example 1: An instance of current LocalTime can be created from the system clock as below:
LocalTime now = LocalTime.now();
Example 2: In the below code sample, we create a LocalTime representing 06:30 AM by parsing a string representation:
LocalTime sixThirty = LocalTime.parse("06:30");
Example 3: The Factory method “of” can be used to create a LocalTime. For example the below code creates LocalTime representing 06:30 AM using the factory method:
LocalTime sixThirty = LocalTime.of(6, 30);
Example 4: The below example creates a LocalTime by parsing a string and adds an hour to it by using the “plus” API. The result would be LocalTime representing 07:30 AM:
LocalTime sevenThirty = LocalTime.parse("06:30").plus(1, ChronoUnit.HOURS);
Example 5: Various getter methods are available which can be used to get specific units of time like hour, min and secs like below:
int six = LocalTime.parse("06:30").getHour();
Example 6: We can also check if a specific time is before or after another specific time. The below code sample compares two LocalTime for which the result would be true:
boolean isbefore = LocalTime.parse("06:30").isBefore(LocalTime.parse("07:30"));
Example 7: The max, min and noon time of a day can be obtained by constants in LocalTime class. This is very useful when performing database queries to find records within a given span of time.
For example, the below code represents 23:59:59.99:
LocalTime maxTime = LocalTime.MAX

1.2 Complete Example for Reference

public class UseLocalTime {

    LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
        return LocalTime.of(hour, min, seconds);
    }

    LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
        return LocalTime.parse(timeRepresentation);
    }

   //Obtains the current time from the system clock in the default time-zone. 
    private LocalTime getLocalTimeFromClock() {
        return LocalTime.now();
    }

    // Returns a copy of this time with the specified amount added. 
    LocalTime addAnHour(LocalTime localTime) {
        return localTime.plus(1, ChronoUnit.HOURS);
    }

    int getHourFromLocalTime(LocalTime localTime) {
        return localTime.getHour();
    }

    LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute) {
        return localTime.withMinute(minute);
    }
}

2. LocalDateTime

The LocalDateTime is used to represent a combination of date and time.

This is the most commonly used class when we need a combination of date and time. The class offers a variety of APIs and we will look at some of the most commonly used ones.

2.1 LocalDateTime Class Examples

Example 1: An instance of LocalDateTime can be obtained from the system clock similar to LocalDate and LocalTime:
LocalDateTime.now();
Example 2: The below code samples explain how to create an instance using the factory “of” and “parse” methods. The result would be a LocalDateTime instance representing 20 February 2015, 06:30 AM:
LocalDateTime.of(2015, Month.FEBRUARY, 20, 06, 30);
LocalDateTime.parse("2015-02-20T06:30:00");
Example 3: Adding days, substract and getting month examples.
localDateTime.plusDays(1);
localDateTime.minusHours(2);
localDateTime.getMonth();

2.2 Complete Example for Reference

public class UseLocalDateTime {

 public static LocalDateTime getLocalDateTimeUsingParseMethod(String representation) {
  return LocalDateTime.parse(representation);
 }

 public static LocalDateTime getCurrentDateTime() {
  return LocalDateTime.now();
 }

 public static void main(String[] args) {
  System.out.println("Current datetime :: " 
            + UseLocalDateTime.getCurrentDateTime());
  System.out.println(" Parse to :: " 
         + UseLocalDateTime.getLocalDateTimeUsingParseMethod("2015-02-20T06:30:00"));
 }
}
Output:
Current datetime :: 2018-07-11T16:02:53.295
Parse to :: 2015-02-20T06:30

Comments