Java Dates, Dandelion, Thymeleaf, Hibernate and Spring

The original title of this blog post was “Easy Java Date Type Handling with Dandelion, Thymeleaf, Hibernate and Spring” but that was a little long. The point is that these frameworks together make handling Java Date types in a web application very easy.

I blogged about Dandelion yesterday and how to configure it with Spring. Dandelion is a very cool framework for handling Javascript, CSS and other types of assets. Dandelion is what loads jQuery-UI which contains the .datepicker calendar in our Contact Form BirthDate field shown below.

Date String Format

If you need to present the date string in a format other than MM/DD/YYYY it would require slightly additional effort and possibly a Spring CustomDateValidator, but here we're sticking with MM/DD/YYYY across the application layers.

Speaking of Dandelion, here is how it loads jQuery-UI to create the calendar. You see that we specify the date format in the .datepicker plugin.

Contact Model BirthDate Annotations

Here are the annotations for our Contact Model's BirthDate Property. To ensure proper Java Date to Hibernate Date Persistence we add a @Temporal annotation. Our BirthDate will appear in the proper format with @DateTimeFormat. We make sure it's not null with @NotNull and add @Past since it's a birth date. We'll see @Past come into play next.

@Past

Using the @Past annotation (javax.validation.constraints.Past) is a great time saver for catching input errors like the following case. A date is selected from the jQuery-UI DatePicker Calendar and a number is added to make the YEAR 19601.

We COULD write a condition in the MVC method like this.

contact.getBirthDate().getTime() > new Date().getTime()

@Past does the work for us, catching the year 19601 as not being in the past and displaying the appropriate messages.properties item, Past.contact.birthDate.

That's it, people. That's our Big Java Date show! The code covered in this post is available in v0.1.5 of Spring NixMash on GitHub.

Posted July 10, 2015 12:31 PM EDT

More Like This Post