Results for tag "date-time"

Java Tip of the Week #5 – Java 8 Date Time API

posted by Roberto Cortez on

Java Tip of the Week - Java 8 Date TimeThis week Java Tip of the Week we are going to continue to look into some of the new features introduced in Java 8. It’s about Time! The new Date Time API.

And in good Time we got it. Have you ever coded a real application without using any kind of object to represent Date or Time? I don’t think so. All of us are obsessed with Time, so it makes sense that we get a first class support to perform all kinds of operations when coding something. This was not the case prior to Java 8.

Java Date Calendar

Before Java 8, working with Date and Time was not an easy task. The old java.util.Date is not thread safe, represents years as two digits, uses a zero based index for months and is mutable. A real mess!

It’s replacement java.util.Calendar, was not much better. Still a mutable class, also with a zero based index for months. Some say it was even more broken than java.util.Date.

Displaying the Date / Time was not exactly easy. You needed to use yet another object to perform the proper formatting with DateFormat.

Finally, I don’t even want to discuss all the trouble you had to work with Timezones.

Here are two of my two “favourite” java.util.Calendar methods:

Calendar add

If I want to calculate yesterday day, but I only have an add method available. What do I do? Add -1 of course. Makes perfect sense!

Calendar set

Set the Month to 20? That can’t possibly work, right? Wrong! java.util.Calendar will just convert this to a valid Month and move the year, meaning that the 20 Months is actually September of the next year. Confused? You should be.

Joda Time

You could fix most of these by using a widely popular Date Time library called Joda Time. Is still the way to go if you can’t use Java 8 yet.

A good thing is that the main developer and creator of Joda Time, Stephen Colebourne was also the spec lead for JSR-310: Date and Time API.

Java 8 Date Time API

Pre Java 8, we need to write this code to print yesterday day, with trunked seconds:

And now:

Check it out in my video:

Remember to follow my Youtube channel for faster updates!

Leave a comment if you enjoyed it, if not leave one as well!

Check some additional information about Java 8 Date Time in the Java Tutorial.