Oracle Certified Associate: Java 8 Date and Time

Java 8 introduces new package for date and time due to many flaws in old version of date and time classes. New package is added named time in java package repository. We required to have basic knowledge about java.time package for Oracle Certified Associate Exam for Java 8.

Whats new in Java 8 Date and Time

This whole article / post is divided in three parts:
  1. java.time package basics.
  2. Manipulating the Date and Time.
  3. Formatting Date and Time.

In this post we will cover the basics of new features in Java8.

java.time package basics
To use data and time in Java 8 use java.time package which have classes related to date and time. Classes are divided for local date and time and timezone relate date and time. Lets see the new classes and what it does.

LocalDate Contains only a data. In Local format.
LocalTime Contains only a time. In Local format.
LocalDateTime Contains date and time. Combination of LocalDate and LocalTime.
ZonedDateTime Contains date, time and timezone.
Instant A point in time in nanoseconds. Used for time stamp.
DayOfWeek Enum, to represent week days like Monday, Tuesday and so on.
Month Enum, to represent months like January, February and so on.

Java 8 supports old way of using Date from java.util also. But for Java 8 certification exam java.time package is considered.

To get current data, time or both now() method is used.

Lets see a simple program to print current date and time.

import java.time.*;
public class Test
    public static void main(String args[])



With new classes the date and time are more human readable or human friendly. "T" is used as separator between date and time.

Next steps is to create a custom date, time or date and time object. In Java 8, we cannot directoy create a object time package using new operator. To create new object static method of is provided. Method of is overloaded method that can be used to create the custom date and time. Lets take an example of creating new date instance for 30-April-2016 and time is 10:30. This can be done using of method as shown in below code

// Passing Year, Month and Date
LocalDate d1 = LocalDate.of(2016,4,30);
// Can also use Month Constant for better readability.
LocalDate d2 = LocalDate.of(2016,Month.April,30); 
// Creating Time with hours and minutes
LocalTime t1 = LocalTime.of(10,30);
// Creating Time with hours, minutes and seconds.
LocalTime t2 = LocalTime.of(10,30,25);
// Creating Time with hours, minutes, seconds and nano seconds
LocalTime t3 = LocalTime.of(10,30,25,20);

We can also combine date and time to create LocalDateTime object with values or passing LocalDate and LocalTime as argument

LocalDateTime dt1 = LocalDateTime.of(2016,4,30,10,30,25);
LocalDateTime dt2 = LocatDateTime.of(d1,t2);

We can also pass LocalDate and LocalTime object for creating new LocalDateTime object.

Next post covers Manipulating the Date and Time.

Labels: , , ,