Friday, September 29, 2017

Java 8 Date Time API: LocalDateTime

With Java 8 Oracle introduced new Date and Time APIs which address the shortcomings of the existing java.util.Date and java.util.Calendar. In this article we will take a look at the Java 8 Date and Time API with few examples of the new LocalDateTime class introduced by Java 8.

Improvements to Existing Calendar and Date Classes

Thread Safety: The existing API was not designed with concurrency in mind. This meant developers had to come up with custom solutions to handle thread safety. The Java 8 Date/Time API ensures thread safety by making all the new classes immutable. Domain-driven design: The Java 8 date/time API has clear domain boundaries, and defines classes with specific use cases. Support for non-standard Calendars: The Java 8 Date/Time API provides support for non-standard calendaring systems (Japanese calendar for example) without affecting the standard calendar implementation.

LocalDateTime

java.time.LocalDateTime, like LocalDate, represents the Time, without the Date. The following examples show show a few ways to use the LocalDateTime class
  • Create an instance of LocalDateTime for current time: The instance representing current time can be obtained using the now() method
    LocalDateTime localDateTime = LocalDateTime.now();
  • Create an instance of LocalDateTime representing a specific time: Again, like LocalDate, there are two variations in which you can instantiate LocalDateTime to represent a specific time:
    • The LocalDateTime.of method takes the distinct elements of the date and time as parameters (year, month, day, hours, minutes, seconds etc.). The following variants are available
      static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
      static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)
      static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
      static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute)
      static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second)
      static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
      static LocalDateTime of(LocalDate date, LocalTime time)
      static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset)
      The following example shows the use of this method
      LocalDateTime specificDateTime1 = LocalDateTime.of(2017, Month.MAY, 21, 21, 30); //  05/21/2017 9:30 PM
      System.out.println(specificDateTime1);
    • The second method is LocalDateTime.parse which again has two variations
      • The default format is DateTimeFormatter.ISO_LOCAL_DATE_TIME, for example : 2017-05-21T21:30:00. The first variant of parse, takes just a string representation of the date and attempts to parse the date by the default format. We can omit the trailing sections of the time, and still be able to parse the time.
        LocalDateTime specificDateTime2 = LocalDateTime.parse("2017-05-21T21:30:00"); 
        System.out.println("With LocalDateTime.parse, and default format : " + specificDateTime2);
      • Custom Date Time Format: In this variation, we can use custom formatting using DateTimeFormatter.ofPattern. In the following example, we will use the parse method to parse a simple time format ("09:30 PM")
        DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm a");
        LocalDateTime specificDateTime4 = LocalDateTime.parse("05-21-2017 09:30 PM", dateTimeFormat); 
        System.out.println("With LocalDateTime.parse, and custom format : " + specificDateTime4);
  • Get parts of the date time: LocalDateTime also provides a few utility method to extract part of the time and get more information about the date
    System.out.println("Hour of the day : " + localDateTime.getHour());
    System.out.println("Minute of the hour : " + localDateTime.getMinute());
  • Add or Subtract with LocalDateTime: LocalDateTime class provides utility methods to add or subtract hours/minutes/seconds (represented by java.time.temporal.TemporalUnit interface). The following examples illustrate the use of these operation on LocalDateTime.
    //Subtract Days
    System.out.println("3 days before now is : " + localDateTime.minus(3, ChronoUnit.DAYS));
    
    //Subtract Minutes
    System.out.println("3 minutes before now is : " + localDateTime.minus(3, ChronoUnit.MINUTES));
    
    //Add Days
    System.out.println("3 days after now is : " + localDateTime.plus(3, ChronoUnit.DAYS));
    
    //Add Minutes
    System.out.println("3 minutes after now is : " + localDateTime.plus(3, ChronoUnit.MINUTES));
  • Compare two LocalDateTimes: The isBefore and isAfter offer a way to compare two LocalDateTime objects
    System.out.println("Is the time after 11:26? " + localDateTime.isAfter(LocalDateTime.parse("2017-05-21T21:30:00")));
    System.out.println("Is the time before 11:30? " + localDateTime.isBefore(LocalDateTime.parse("2017-05-21T21:30:00")));
  • Time between two LocalDateTimes: The until() method provides a way to calculate the number of hours/minutes etc between two LocalDateTimes. This method takes in the end time and TemporalUnit as a parameter, and can be used to calculate the number hours, minutes etc. between the start time and end time.
    System.out.println("Number of hours from now to 2018-05-21T21:30:00: " + localDateTime.until(LocalDateTime.parse("2018-05-21T21:30:00"), ChronoUnit.HOURS));
    System.out.println("Number of minutes from now to 2018-05-21T21:30:00: " + localDateTime.until(LocalDateTime.parse("2018-05-21T21:30:00"), ChronoUnit.MINUTES));

Full Class file for this test

import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class LocalDateTimeExamples {

 public static void main(String[] args) {

  LocalDateTime specificTime1 = LocalDateTime.of(2017, Month.MAY, 21, 21, 30); // 9:30 PM
  System.out.println("With LocalDateTime.of : " + specificTime1);

  LocalDateTime specificDateTime2 = LocalDateTime.parse("2017-05-21T21:30:00");
  System.out.println("With LocalDateTime.parse, and default format : " + specificDateTime2);

  DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm a");
  LocalDateTime specificDateTime4 = LocalDateTime.parse("05-21-2017 09:30 PM", dateTimeFormat);
  System.out.println("With LocalDateTime.parse, and custom format : " + specificDateTime4);

  LocalDateTime localDateTime = LocalDateTime.now();
  System.out.println("Hour of the day : " + localDateTime.getHour());
  System.out.println("Minute of the hour : " + localDateTime.getMinute());

  // Subtract Days
  System.out.println("3 days before now is : " + localDateTime.minus(3, ChronoUnit.DAYS));

  // Subtract Minutes
  System.out.println("3 minutes before now is : " + localDateTime.minus(3, ChronoUnit.MINUTES));

  // Add Days
  System.out.println("3 days after now is : " + localDateTime.plus(3, ChronoUnit.DAYS));

  // Add Minutes
  System.out.println("3 minutes after now is : " + localDateTime.plus(3, ChronoUnit.MINUTES));

  System.out.println("Is the time after 11:26? " + localDateTime.isAfter(LocalDateTime.parse("2017-05-21T21:30:00")));
  System.out.println("Is the time before 11:30? " + localDateTime.isBefore(LocalDateTime.parse("2017-05-21T21:30:00")));

  System.out.println("Number of hours from now to 2018-05-21T21:30:00: "
    + localDateTime.until(LocalDateTime.parse("2018-05-21T21:30:00"), ChronoUnit.HOURS));
  System.out.println("Number of minutes from now to 2018-05-21T21:30:00: "
    + localDateTime.until(LocalDateTime.parse("2018-05-21T21:30:00"), ChronoUnit.MINUTES));

 }
}

No comments:

Post a Comment

Popular Posts