Reputation: 3992
On this page i read the following:
To do calculations with dates, it is also very easy. Probably the best improvement compared to the current situation with Java < 1.8:
Period p = Period.of(2, HOURS);
LocalTime time = LocalTime.now();
LocalTime newTime = time.plus(p); // or time.plus(5, HOURS); or time.plusHours(5);
I don't clearly see the advantage prior to Versions < 1.8.
Maybe someone can give me an example? Atm i am asking myself, where the improvement of the new date & time API comes from.
Upvotes: 12
Views: 14023
Reputation: 1985
Advantages of the new date/time API
Disadvantages
Upvotes: 2
Reputation: 328893
With Java < 8, you would need to write something like:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) + 2);
vs. with Java 8:
LocalTime now = LocalTime.now();
LocalTime later = now.plus(2, HOURS);
The improvements are essentially on
Calendar.getInstance()
is not very well named: it is hard to tell which instance you are getting without reading the Javadoc. LocalTime.now()
is quite self-describing: you get a time and it is now.plus
) whereas with the Calendar API, you have to manually change the fields of the object (in this example, the hour) which is error prone.cal.set(123, 2)
which would throw a not-so-helpful ArrayOutOfBoundsException
. The new API uses enums which solves that problem.Overall, the new API is significantly inspired from jodatime which has been the preferred Java Date API for quite some time now. You can also read this detailed comparison of Java (<1.8) date vs. JodaTime (most of it should apply to the Java 8 Date API).
Upvotes: 29