New Date &Time API from JDK 8



New Date & Time API from JDK 8


Date and Time handling in Java was tricky and not thread safe. Current system time can be accessed via he static method System.currentTimeMillis()  which returns the current time in milliseconds. Even though java.util.Date is there, it does not provide lot of date and time related functions that are convenient to the developer.In other words Date and Calendar API are not much developer friendly as other API for a long time,  most developers tend to Joda Date Time  library due to these reasons. This latest JDK 8 release Java team revolutionize the Date and Time api and introduced full featured thread safe, developer friendly API.
It drag my attention to try out new API features.

Following will explain the new features with some sample code snippets.

New Structure of the Date Time API


  • java.time : This is the base package of new Java Date Time API. All the major base classes are part of this package, such as LocalDate, LocalTime, LocalDateTime, Instant, Period, Duration etc. All of these classes are immutable and thread safe. Most of the times, these classes will be sufficient for handling common requirements.
  • java.time.chrono : This package defines generic APIs for non ISO calendar systems. We can extend AbstractChronology class to create our own calendar system.
  • java.time.format : This package contains classes used for formatting and parsing date time objects. Most of the times, we would not be directly using them because principle classes in java.time package provide formatting and parsing methods.
  • java.time.temporal : This package contains temporal objects and we can use it for find out specific date or time related to date/time object. For example, we can use these to find out the first or last day of the month. You can identify these methods easily because they always have format “withXXX”.
  • java.time.zone : This package contains classes for supporting different time zones and their rules.

  Create Date and Time instances.

  LocalDate date = LocalDate.now();
  LocalDateTime dateTime = LocalDateTime.now();

  // With time zones, valid time zones
  LocalDateTime time = LocalDateTime.now(ZoneId.of("Asia/Singapore"));


Get milliseconds from a Date and Time

  LocalDate date = LocalDate.now(); 
  long millis = date.atZone(ZoneId.of("Asia/Singapore")).toInstant().toEpochMilli();

    Get times of different Time zones

   LocalDateTime time = LocalDateTime.now(ZoneId.of("Asia/Singapore"));
   ZonedDateTime pacificTime = time.atZone(ZoneId.of("Pacific/Apia"));
   ZonedDateTime mexicoTime = time.atZone(ZoneId.of("America/Mexico_City"));

    Plus or minus values from the date

  
   LocalDate date = LocalDate.now(); 
   date.plusXXX(amountToAdd); // add mins, hours, days etc.

   date.minusXXX(amountToSubtract); // subtract mins, hours, days etc.

    Format Date and Time

   date.format(formatter); // Can use inbuilt for-matter or own pattern.

   Get Date and Time from a text

   date.parse(text) // Parse a text to get the LocalDateTime

  Clock  - The current time is represented by the Clock class.
   Clock clock = Clock.systemDefaultZone();
   long clockMilis = clock.millis();

    // with time zone
   ZoneId zone = ZoneId.systemDefault();
   Clock clock = Clock.system(zone);

  Period and Duration

       
     Period : To define an amount of time with date-based values (years, months, days), use the 
Period class
 

   public static void period() {
 LocalDate today = LocalDate.now();
 LocalDate birthday = LocalDate.of(1986, Month.DECEMBER, 14);

 Period p = Period.between(birthday, today);
 long p2 = ChronoUnit.DAYS.between(birthday, today);
 System.out.println("You are " + p.getYears() + " years, "
   + p.getMonths() + " months, and " + p.getDays()
   + " days old. (" + p2 + " days total)");

   }


  // eg #2
  
  import javax.time.LocalTime;
  import javax.time.Period;


  LocalTime time = LocalTime.now();
  LocalTime newTime;
  newTime = time.plus(5, HOURS);
 // or
  newTime = time.plusHours(5);
  Duration: Duration is most suitable in situations that measure machine-based time, secs, minutes, hours, etc.
   Instant t1, t2;
   ...
   long ns = Duration.between(t1, t2).toNanos();


   Example : Following example will print the date and time on a different time zones and calculates the duration to current time from a given timestamp using new API.

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * * JavaNewTimeTest
 * 


 *
 *
 * @author Amila Silva
 *
 */
public class JavaNewTimeTest {

 public static void main(String[] args) {
  LocalDateTime time = LocalDateTime.now(ZoneId.of("Asia/Singapore"));

  System.out.println(":: Local Time           :" + time);
  System.out.println(":: Pacific/Apia         :"
    + time.atZone(ZoneId.of("Pacific/Apia"))
    + " : Milis ["
    + time.atZone(ZoneId.of("Pacific/Apia")).toInstant()
      .toEpochMilli() + "]");
  System.out.println(":: America/Mexico_City  :"
    + time.atZone(ZoneId.of("America/Mexico_City"))
    + " : Milis ["
    + time.atZone(ZoneId.of("America/Mexico_City")).toInstant()
      .toEpochMilli() + "]");
  System.out.println(":: Australia/Melbourne  :"
    + time.atZone(ZoneId.of("Australia/Melbourne"))
    + " : Milis ["
    + time.atZone(ZoneId.of("Australia/Melbourne")).toInstant()
      .toEpochMilli() + "]");

  LocalDateTime date = LocalDateTime.now(ZoneId.of("Asia/Singapore"));
  System.out.println(":: Apia :"
    + date
    + "        : Milis ["
    + date.atZone(ZoneId.of("Pacific/Apia")).plusWeeks(2)
      .toInstant().toEpochMilli() + "]");

  date = LocalDateTime.now(ZoneId.of("America/New_York"));
  System.out.println(":: New York time :"
    + date
    + " : Milis ["
    + date.atZone(ZoneId.of("America/New_York")).toInstant()
      .toEpochMilli() + "]");

  date = LocalDateTime.now(ZoneId.of("Australia/Melbourne"));
  System.out.println(":: Melbourne :"
    + date
    + "   : Milis ["
    + date.atZone(ZoneId.of("Australia/Melbourne")).toInstant()
      .toEpochMilli() + "]");

  // WORLD TIME
  getWorldTimeDiff();
 }

 public static void getWorldTimeDiff() {
  System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

  LocalDateTime localTime = LocalDateTime
    .now(ZoneId.of("Asia/Singapore"));

  long timestamp = localTime.atZone(ZoneId.of("Asia/Singapore"))
    .toInstant().toEpochMilli();

  long tempStamp = 1412151163990L;

  // Time in NewYork
  LocalDateTime timezoneDate = getTimezoneValue(tempStamp,
    ZoneId.of("America/New_York"));
  ZoneId zoneId = ZoneId.of("America/New_York");
  System.out.println(":: NewYork  :" + timezoneDate + " Diff : "
    + timeAgo(timezoneDate, zoneId));

  // Time in Sydney
  timezoneDate = getTimezoneValue(tempStamp,
    ZoneId.of("Australia/Sydney"));
  zoneId = ZoneId.of("Australia/Sydney");
  System.out.println(":: Sydney   :" + timezoneDate + " Diff : "
    + timeAgo(timezoneDate, zoneId));

  // Time in Canada
  timezoneDate = getTimezoneValue(tempStamp,
    ZoneId.of("America/Vancouver"));
  zoneId = ZoneId.of("America/Vancouver");
  System.out.println(":: Canada   :" + timezoneDate + " Diff : "
    + timeAgo(timezoneDate, zoneId));

  // Time in Italy
  timezoneDate = getTimezoneValue(tempStamp, ZoneId.of("Europe/Rome"));
  zoneId = ZoneId.of("Europe/Rome");
  System.out.println(":: Italy    :" + timezoneDate + " Diff : "
    + timeAgo(timezoneDate, zoneId));
 }

 private static LocalDateTime getTimezoneValue(long timestamp, ZoneId zoneId) {
  return Instant.ofEpochMilli(timestamp).atZone(zoneId).toLocalDateTime();
 }

 private static String timeAgo(LocalDateTime dateTime, ZoneId zoneId) {
  Duration duration = Duration.between(dateTime,
    LocalDateTime.now(zoneId));

  if (duration.toHours() >= 1) {
   return duration.toHours() + " hours ago";
  } else if (duration.toMinutes() <  60 && duration.toMinutes() > 0 ) {
   return duration.toMinutes() + " mins ago";
  } else if (duration.getSeconds() < 60 && duration.getSeconds() > 5) {
   return duration.getSeconds() + " sec ago";
  } else {
   return "Now";
  }
 }
}



References :

  1.   http://docs.oracle.com/javase/tutorial/datetime/iso/period.html
  2.   http://java.dzone.com/articles/introducing-new-date-and-time
  3.   http://www.journaldev.com/2800/java-8-date-time-api-example-tutorial-localdate-instant-localdatetime-parse-and-format




Comments

Popular posts from this blog

PostgreSQL bytea and oid

MySQL as Hive metadata store

Big Memory Go.