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
- New Package java.time.
- Classes for more human friendly output i.e only date, only time, Date and Time, Timezone Date and Time.
- Different class for local and timezone date time.
- Date and Time counting starts with 1, yes not 0.
- Thread Safe, no need to worry about concurrency control.
- All date and time in new package are Immutable.
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.
||Contains only a data. In Local format.
||Contains only a time. In Local format.
||Contains date and time. Combination of LocalDate and LocalTime.
||Contains date, time and timezone.
||A point in time in nanoseconds. Used for time stamp.
||Enum, to represent week days like Monday, Tuesday and so on.
||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.
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.