16

I have a Joda-DateTime field in my model and want to display it formatted in a JSP view. I have annotated it with the new @DateTimeFormat annotation:

public class Customer {
   private DateTime dateOfBirth;

   @DateTimeFormat(style="M-")
   public DateTime getDateOfBirth() {
      return dateOfBirth;
   }
}

Now I want to display the dateOfBirth in my JSP:

Date of birth: ${customer.dateOfBirth}

But the result is unformatted:

Date of birth: 2010-08-11T11:23:30.148+02:00

After some research I found out, that I have to use the spring:bind-tag:

<spring:bind path="customer.dateOfBirth">
   Date of birth: ${status.value}
</spring:bind>

With this it works. But it seems too complicated for this simple task. And using this method on lists is even more complicated since you have to integrate the list-index into the binding-path.

So my question is: Is there a simpler way to display a formatted value using the spring formatting-annotations?

Florian Fankhauser
  • 3,615
  • 2
  • 26
  • 30

3 Answers3

19

Because its a joda datetime object, and not a Date object, you will have to write your own formatting function or a custom tag.

If you can convert it to java.util.Date somehow, then you can use the built in jstl's fmt taglibrary.

<fmt:formatDate value="${customer.dateOfBirth}" type="both" 
      pattern="MM-dd-yyyy" />

But the latest jsp quickly allows you to create custom tags.

naikus
  • 24,302
  • 4
  • 42
  • 43
19

Use the spring:eval tag which understands the @DateTimeFormat rule:

<spring:eval expression="customer.dateOfBirth" />

Alternatively, you can remove the @DateTimeFormat rule from your model all-together and use Joda's formatDate tag as Naikus illustrates.

In a future release, Spring plans to support plugging in "SpEL", which is the "Spring Expression Language" invoked by spring:eval, as the default Unified EL implementation for your JSP pages. This would allow in-line expressions like ${customer.dateOfBirth} to be routed through SpEL as well. You can vote up this enhancement request here: https://jira.spring.io/browse/SPR-7459.

tk_
  • 16,415
  • 8
  • 80
  • 90
kdonald
  • 511
  • 2
  • 7
  • Spring:eval works great. Besides I upvoted the enhancement request for integrating SpEL in JSP. Thank you. – Florian Fankhauser Aug 11 '10 at 20:38
  • I found a small issue with spring:eval in version 3.0.3. When the expression evaluates to null, the string 'null' is printed. In contrast, the spring:bind example from my question prints an empty string when the expression evaluates to null. Is there a way to suppress the output of 'null'? Thanks. – Florian Fankhauser Aug 11 '10 at 21:43
0

Spring gives us the option to set global date-time formats via the application properties file. Just add this config to application.properties:

spring.mvc.format.date=yyyy-MM-dd
spring.mvc.format.date-time=yyyy-MM-dd HH:mm:ss
spring.mvc.format.time=HH:mm:ss
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61