- 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.
This whole article / post is divided in three parts:
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.
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
// Can also use Month Constant for better readability.
// Creating Time with hours and minutes
// Creating Time with hours, minutes and seconds.
LocalTime t2 = LocalTime.of(10,30,25);
// Creating Time with hours, minutes, seconds and nano seconds
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.