New Date and Time API In Java 8

Posted By : Ranjan Mondal | 30-Apr-2018

Introduction: Java 8 introduces a brand new Date and Time api which helps us in doing data and time related tasks efficiently and easily. Java's handling of Date, Calendar and Time was very troublesome process.

 

Benefits :

Immutablity: All the classes in Time and Date api are immutable and Thread Safe.

Clarity: All the classes use Factory Pattern and Strategy Pattern for better handling.

Utility Operations: All new Date Time classes comes with methods to perform task like plus, minus, format, parsing etc.

 

Local Date represents date without the time. It has static methods now which give a current date.

    LocalDate now = LocalDate.now();
    System.out.println("Today Date : " + now);    
   

By using methods on LocalDate instance You can get following Details.
Day by today.getDayOfMonth()
Month in integer today.getMonthValue() and String today.getMonth()
Year by today.getYear()

 

We can create LocalDate Object by passing day, month and year values in Factory Method of LocalDate

    LocalDate localDate = LocalDate.of(2018, 1, 29);  
   

It did not do the same mistake like month start from 0 so on.
Everything is simple and crisp here.

 

Comparing two dates is a very important task like today is birthday or Govt. holiday or not.
For this, LocalDate overrides equal methods to tell both are equal or not.

    LocalDate localDate = LocalDate.of(2018, 5, 20);
    LocalDate today = LocalDate.now(); // run on 5 May, 2018
    today.equals(localDate) returns true.
    
 

 

In a real application like E-commerce, we need to send email on customer's birthday, reminding of monthly installments.
So we can easily calculate today is a date or not by using MonthDay class.

   LocalDate birthday = LocalDate.of(1990, 6, 4);
   MonthDay monthDay = MonthDay.of(birthday.getMonth(), birthday.getDayOfMonth());
   MonthDay currentMonthDay = MonthDay.from(monthDay);
   currentMonthDay.equals(monthDay) return true   
   

 

There is another class of LocalTime which represent time only not date.
LocalTime localTime = LocalTime.now();

Gives localTime = 16:33:33.369  which is hh:mm:ss.nnn  where nnn repressent nano seconds.

 

A Utility method is given in LocalTime to add hours, 

    localTime = localTime.plusHours(4);
   

 

LocalTime is immutable and threadsafe, so it gives a new instance. So we have to store it.

Like before, we have another method

   localDate = localDate.plus(1, ChronoUnit.WEEKS);
    eg of ChronoUnit are ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MONTHS etc   
   

We have opposite method of plus is minus.

    LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
   

We can use any value by using ChronoUnit Enum.

 

We can compare LocalDate Object by isBefore() and isAfter()

    yesterdayLocalDate.isBefore(today)  returns true.
    tomorrowLocalDate.isAfter(today) return true.          
   

 

boolean isLeapYear() of LocalDate tell where the current year is a leap year or not.

   LocalDate localDate = LocalDate.of(2016,Month.JUNE, 1);
   System.out.println(localDate.isLeapYear()); return true
   

One of the common tasks is to calculate days, weeks, months or year between two dates.
In Java 8, we have Period class. It has method between(startDate, endDate) when we pass two dates and we get an instance of Period.

From there we can we get respective information, example below.

   LocalDate localDate = LocalDate.of(2016,Month.JUNE, 1);
   LocalDate now = LocalDate.now();
   Period period = Period.between(localDate, now);
        
   System.out.println("Year : " + period.getYears());
   System.out.println("Month : " + period.getMonths());
   System.out.println("Days : " + period.getDays()); 
   

 

You can also create new date by adding Offset which is ZoneOffset by Using class OffsetDateTime.

   LocalDateTime localDateTime = LocalDateTime.now();
   ZoneOffset zoneOffset1 = ZoneOffset.of("+04:30");
   OffsetDateTime offsetDateTime = OffsetDateTime.of(localDateTime, zoneOffset1); 
   

If you need a current timestamp, You can use Instant class. It is similar to Date in java.util.

    Instant timestamp = Instant.now();
    System.out.println("Timestamp : " + timestamp); 
   

Parsing Date from String is now very easy in Java 8.

   LocalDate formatted = LocalDate.parse("20180225", DateTimeFormatter.BASIC_ISO_DATE);
    try {
            formatted = LocalDate.parse("Jun 01 2015", DateTimeFormatter.ofPattern("MMM dd YYYY"));
            System.out.println(formatted);
    }catch (Exception e) {
    }

You can reconvert LocalDate to desired string format 

   try {
        String dateInString = formatted.format( DateTimeFormatter.ofPattern("MMM dd YYYY"));
        System.out.println(dateInString);
   }catch (Exception e){
   }

   

About Author

Author Image
Ranjan Mondal

Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..