Srikanth Technologies

New Date and Time API in Java 8

Java8 has introduced new Date and Time API that is superior to the existing one with Date and Calendar classes. The new API is developed under JSR 310 and uses calendar system defined in ISO-8601 as the default calendar.

The following are important enhancements to Date and Time API.

Important packages

The following are important packages related to date and time introduced in Java8.

java.time

The core of the API for representing date and time. It includes classes for date, time, date and time combined, time zones, instants, duration, and clocks. These classes are based on the calendar system defined in ISO-8601, and are immutable and thread-safe.

java.time.format

Contains classes for formatting and parsing dates and times.

java.time.zone

Contains classes that support time zones, offsets from time zones, and time zone rules. Most developers will need to use only ZonedDateTime, and ZoneId or ZoneOffset.

LocalDate class

A LocalDate represents a year-month-day in the ISO calendar and is useful for representing a date without a time. You might use a LocalDate to track a significant event, such as a birth date or wedding date.

   LocalDate date = LocalDate.of(1998, Month.OCTOBER, 24);  // create date from 1998-10-24
   LocalDate newdate = date.plusDays(100);                  // add 100 days to it
       
   LocalDate dob = LocalDate.parse("1998-02-28");                                                        // create date from string 
   LocalDate dob2 = LocalDate.parse("09-10-2002", DateTimeFormatter.ofPattern("dd-MM-uuuu"));            // create date from string using formatter 

LocalTime Class

LocalTime represents a time without a timezone.

  LocalTime now = LocalTime.now();    // get current time
  System.out.println(now);
          
  LocalTime singtime = LocalTime.now(ZoneId.of("Asia/Singapore"));  // get time in timezone Asia/Singapore
  System.out.println(singtime);

  LocalTime starttime = LocalTime.of(9,30,00);      // create time from hours, mins, secs
  LocalTime endtime   = starttime.plusMinutes(105);  // add 105 minutes and get new time

LocalDateTime class

This class handles both date and time, without a time zone. This class is used to represent date (month-day-year) together with time (hour-minute-second-nanosecond) and is, in effect, a combination of LocalDate with LocalTime.

YearMonth class

This represents the month of a specific year.

  YearMonth  dj = YearMonth.of(2012, Month.FEBRUARY);
  System.out.println(dj.lengthOfMonth());               // 29
  System.out.println(dj.plus(10, ChronoUnit.MONTHS));   // add 10 months to dj

MonthDay

This represents the day of a particular month, such as New Year's Day on January 1.
  MonthDay  today = MonthDay.now();
  System.out.println(today.getMonthValue()); 

Year Class

This represents a year.
  Year y = Year.of(2012);
  System.out.println( y.isLeap());

ZoneId and ZoneOffset classes

ZoneId specifies a time zone identifier and provides rules for converting between an Instant and a LocalDateTime. ZoneOffset specifies a time zone offset from Greenwich/UTC time.

ZonedDateTime handles a date and time with a corresponding time zone that is offset from Greenwich/UTC.
 
    // display date and time of leaving in India and arriving in Singapore 
    ZoneId leavingZone =  ZoneId.of("Asia/Calcutta");
    ZonedDateTime departure = ZonedDateTime.now(leavingZone);

    ZoneId arrivingZone =  ZoneId.of("Asia/Singapore");
    ZonedDateTime arriving = departure.withZoneSameInstant(arrivingZone).plusHours(3);
    
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING :  %s (%s)%n", out, leavingZone);
    
    out = arriving.format(format);
    System.out.printf("ARRIVING:  %s (%s)%n", out, arrivingZone);

TemporalAdjusters class

The TemporalAdjusters class provides a set of predefined adjusters for finding the first or last day of the month, the first or last day of the year, the last Wednesday of the month, or the first Tuesday after a specific date, to name a few examples.

 LocalDate date = LocalDate.of(2014, Month.MAY, 15);
 System.out.printf("first day of Month: %s%n", date.with(TemporalAdjusters.firstDayOfMonth()));
 System.out.printf("first Monday of Month: %s%n",date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));

Age calculator program

The following program displays the age of the person in years, months and days.
 import java.time.LocalDate;
 import java.time.Period;
 import java.time.temporal.ChronoUnit;
 import java.util.Scanner;
 public class AgeCalculator {
   public static void main(String[] args) {
    System.out.print("Enter date of birth [yyyy-mm-dd]:");
    Scanner s = new Scanner(System.in);
    String dobstr = s.nextLine(); 
        
    LocalDate dob = LocalDate.parse(dobstr);
    LocalDate now = LocalDate.now();
        
    Period  p = Period.between(dob,now);
    System.out.printf("%d years,%d months and %d days  old!\n",p.getYears(), p.getMonths(), p.getDays());
   }
 }
The above are some of the classes provided by new Date and Time API. For complete API, please refer to Java documentation here.

Also refer to Java Tutorial on Date and Time API for more information about how to use Date and Time API.