Mock Java Date/Time for Testing

Referencing the current date/time in your source code makes testing pretty difficult. You have to exclude such references from your assertions, which is not a trivial task to complete.

Time mocking is a viable solution to avoiding current time inconveniences during testing, which can be accomplished by using the new Java 8 Date/Time API (JSR 310).

Practical Guide For Converting Between Date and Temporal

Check out this guide on how to convert between Date and Temporal classes in Java.

This article will cover the following Temporal classes— Instant,  LocalDate,  LocalDateTime,  ZonedDateTime, OffsetDateTime,  LocalTime , and OffsetTime.

You may also like: Java Date and Time

Date – Instant

In order to convert from Date to Instant, the solution can rely on the Date.toInstant() method. The reverse can be accomplished via the Date.from(Instant instant) method:

Java 8 Java.Time Package: Parsing Any String to Date [Code Snippets]

In one of my projects, I received a requirement that stated that while parsing a text file, Strings denoting a date or a timestamp are expected to be in many different formats that are not known in advance, yet all of them represent a valid date or timestamp needed to be parsed properly. So, the solution I came up with is this: To have a set of formats stored in the property file, and when a String needs to be parsed, the formats are read from a file and attempts to parse the String are made sequentially with each format until it is parsed successfully, or until we run out of formats. The advantages of this solution are that if you discover a valid String that was not parsed successfully, all you will need to do is to add a new format to your properties file and no re-compilation and re-deployment is needed. Also, this way, you can set your priorities: Say if the US date format is preferable to the European one, just place US formats first and only after the European ones. Also, in Java 8, the format Strings allow for the optional format sections denoted by '[]'. So, several formats actually may be combined into a single one with optional sections. For example, instead of:

MM/dd/yyyy

MM-dd-yyyy

MM.dd.yyyy