Friday, June 15, 2018

Java SE 8 Date and Time API

Time is a scalar quantity, so it would only need a number to express a time value.
Since you want to relate time to calendars, which are made for humans, things get more complicated.

Java date and time classes' history:

  • the java.util.Date class was introduced in Java 1.0
  • the java.util.Calendar class was introduced in Java 1.1
  • third-party date and time libraries, such as Joda-Time, were used by developer to overcome Java standard API's issues
  • the java.time API was introduced in Java 1.8 to fix the flaws in the previous versions of the platforms

1 The Time Line

The unit of time is the second, which is derived from the Earth's rotation around its axis.

Universal Time

  • Earth rotation is not uniform: in 1967, a more precise definition of second was derived from the property of atoms of caesium-133 and atomic clocks were introduced to keep the official time.
  • Since rotation rate of Earth varies with climate events, official time keepers synchronize absolute time with solar mean time
    • official time keepers add or remove a second to keep the Universal Time close to the mean solar time
  • In UTC, a day has 24 * 60 * 60 = 86400 seconds.
    • the number of seconds in a minute is usually 60, but with an occasional leap second it may be 61.

Universal Time and Computer Systems

  • Computer system keeps 86400 seconds per day and do not respect leap seconds.
  • when a leap second is officially introduced, computer systems slow down or speed up before the leap second.

Java Date and Time API specification for the time scale:

  • A day has 86,400 seconds
  • Time scale matches the official time at noon each day

The Time Line in Java and the Instant class

  • the Instant class represents a point in the time line
  • The static method Instant.now() returns the current instant
  • time is measured on time scale with origin set at midnigth of January 1, 1970 at Greenwich meridian
  • from that origin, time is measured in 86,400 seconds per day
  • Instant.MIN and Instant.MAX are one billion behind and ahead the origin

The Duration class represents the amount of time between two instants

  • the static method Duration.between gives the difference between two instants

Example:

 Instant start = Instant.now();
 callMethod();
 Instant stop = Instant.now();
 Duration timeElapsed = Duration.between(start, stop);
 long millis = timeElapsed.toMillis();