Preface
Wikipedia defines Time as:
"Time is a measure in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.Time is often referred to as the fourth dimension, along with the three spatial dimensions."
Since Time is a natural concept, in an ideal world, dealing with it should be simple, but unfortunately it is not the case and we humans made it more complex by introducing different time zones and day light saving.
As a programmer, we want that programming languages immune us from these complexity and being a Java programmer, we have similar expectations from Java. Java tried to overcome these complexities in its first two editions of Date and Time API, but failed measurably. A simple google will give you numerous posts criticizing Java for this. Few years back, I was introduced to Joda-Time library that provide APIs that help you to work with Time with ease.
In its latest edition (Java 8), in its third attempt, finally Java brought this change that we all were looking for long. With its new APIs, it is no more require to use either third party APIs or create several utility classes/methods to deal with date and time. This new API is heavily inspired by Joda-Time library.
Java 8 - Date and Time API
New API defines classes to map the concepts of Instant, Duration, Period, Time (Local and Zoned). All the classes are immutable and thread safe. Official java.time package summary offers a great detail on the different concepts and worth a visit.
Instant and Duration:
Wikipedia defines Time as:
"Time is a measure in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.Time is often referred to as the fourth dimension, along with the three spatial dimensions."
Since Time is a natural concept, in an ideal world, dealing with it should be simple, but unfortunately it is not the case and we humans made it more complex by introducing different time zones and day light saving.
As a programmer, we want that programming languages immune us from these complexity and being a Java programmer, we have similar expectations from Java. Java tried to overcome these complexities in its first two editions of Date and Time API, but failed measurably. A simple google will give you numerous posts criticizing Java for this. Few years back, I was introduced to Joda-Time library that provide APIs that help you to work with Time with ease.
In its latest edition (Java 8), in its third attempt, finally Java brought this change that we all were looking for long. With its new APIs, it is no more require to use either third party APIs or create several utility classes/methods to deal with date and time. This new API is heavily inspired by Joda-Time library.
Java 8 - Date and Time API
New API defines classes to map the concepts of Instant, Duration, Period, Time (Local and Zoned). All the classes are immutable and thread safe. Official java.time package summary offers a great detail on the different concepts and worth a visit.
Instant and Duration:
In Java, an Instant represents a point on the time line. An origin, called the epoch, is arbitrarily set at midnight of January 1, 1970 GMT. This is the same convention used in the Unix/POSIX time. Starting from that origin, time is measured in 86,400 seconds per day, forwards and backwards, in nanosecond precision. Instant is essentially a timestamp.
Duration is amount of time between two instants. Both instants and duration are scalar values, that mean time zone or day light saving doesn't affect them.
Getting Current Instant:
Getting Current Instant:
Instant instant = Instant.now();
Duration between two instants:
Instant startInstant = Instant.now(); Instant endInstant = Instant.now(); Duration duration = Duration.between(startInstant,endInstant);
Adding time to a duration is pretty straight forward:
public void editDuration(Duration duration){ // Enhance Duration by 5 minutes Duration enhanceDurationByMinute = duration.plusMinutes(5); //Enhance Duration by 2 Days, 5 hours, 6 minutes, // 10 Seconds, 200 milliseconds and 788 nanoseconds Duration enchanced = duration.plusDays(2).plusHours(5).plusMinutes(6) .plusSeconds(10).plusMillis(200).plusNanos(788); }
Important point to note here is, since Duration is an immutable, every time you call a plusXXX() method, it returns a new object of Duration.
Duration stores time in two parts, seconds and nano seconds and provide two methods to get these parts. It provides methods to get total time in different units viz. milliseconds, minutes, hours.
Getting Duration in human readable form:
public static void getDurationBetweenTwoInstants(){ Logger logger = Logger.getGlobal(); Instant startInstant = Instant.now(); for(int i = 0; i < Integer.MAX_VALUE; i++){ //Do nothing } Instant endInstant = Instant.now(); Duration duration = Duration.between(startInstant, endInstant); logger.log(INFO, "" + duration); duration = duration.plusHours(5).plusMinutes(8).plusSeconds(2) .plusMillis(234).plusNanos(234); logger.log(INFO, "Total Time :" + duration); logger.log(INFO, "NanoSecond Part of Total Time: " + duration.getNano()); logger.log(INFO,"Seconds Part of Total Time: " + duration.getSeconds()); logger.log(INFO,"Total time in Nano : " + duration.toNanos()); logger.log(INFO,"Total time in Millis : " + duration.toMillis()); logger.log(INFO,"Total time in Minutes : " + duration.toMinutes()); logger.log(INFO,"Total time in Hours : " + duration.toHours()); }
A sample Output of above program looks like:
INFO: Time in looping: PT0.006S
INFO: Total Time :PT5H8M2.240000234S
INFO: NanoSecond Part of Total Time: 240000234
INFO: Seconds Part of Total Time: 18482
INFO: Total time in Nano : 18482240000234
INFO: Total time in Millis : 18482240
INFO: Total time in Minutes : 308
INFO: Total time in Hours : 5
INFO: Total Time :PT5H8M2.240000234S
INFO: NanoSecond Part of Total Time: 240000234
INFO: Seconds Part of Total Time: 18482
INFO: Total time in Nano : 18482240000234
INFO: Total time in Millis : 18482240
INFO: Total time in Minutes : 308
INFO: Total time in Hours : 5
Similar methods exists for subtraction as well.
Conclusion
Instants and Duration is the basis of new Date and Time API. But as you can see, both the APIs are not that useful from human being interaction and for that there are other APIs that relates to Periods, Local and Zoned Date/Time. I will discuss about them in my next post.