Working with Dates

Date and Time Classes

This is quite a big subject but the short summary is that with Java 8 and later you should be using LocalDateTime (or LocalDate or LocalTime) or ZonedDateTime, where LocalDateTime is fine if you don't need to support anything other than the local time zone. The date & time classes prior to Java 8 were not thread safe and time zone handling was more difficult, so ideally avoided.

When creating dates then it is recommended that you use the Month (Java Platform SE 8 ) enum and possibly DayOfWeek (Java Platform SE 8 ) as well.

There are other interesting classes:

There are also classes for working with different timezones and their offsets.

It is also worth having a look at DateTimeFormatter (Java Platform SE 8 ) which is very handy for formatting the date and/or time for output or display. The FormatStyle (Java Platform SE 8 ) enum is also handy.

With Java 7 and earlier we used java.util.Date and java.util.Calendar, these should be avoided now and indicate a "bad smell".

Difference Between Times

This is a common problem, how long did some thing take and a common one with batch jobs, which is where this example comes from:

import java.time.Duration;

Duration d = Duration.between(jobExecution.getStartTime().toInstant(), jobExecution.getEndTime().toInstant());
log.info("Job Duration: {} in ISO-8601 format", d)

It does not show all the code, just the bits you need. This only works from Java 8 onwards, when Duration was added and so was the toInstant() method on java.util.Date.