The @DateTimeFormat annotation has three mutually exclusive attributes that determine the format of the date and time, which is displayed in the screen. These are: style, iso and pattern. When no attributes are applied to @DateTimeFormat the annotation defaults to style=”SS”.
Below is an example of the annotation being applied to a java.util.Calendar object:
@DateTimeFormat(iso = DateTimeFormat.ISO.NONE)
private final Calendar datetime;
The style attribute can be set to either Short, Medium, Long or Full. The table below demonstrates that kind of output you’ll get using the style attribute. Note that here I say ‘kind of’ as the formatting in locale specific; in the examples below, my locale was set to en_US.
Style | Result |
---|---|
SS | 7/11/11 8:54 PM |
-S | 8:54 PM |
S- | 7/11/11 |
MM | Jul 11, 2011 8:56:37 PM |
-M | 8:59:45 PM |
M- | Jul 11, 2011 |
LL | July 11, 2011 9:02:53 PM BST |
-L | 9:02:53 PM BST |
L- | July 11, 2011 |
FF | Monday, July 11, 2011 9:05:35 PM BST |
-F | 9:05:35 PM BST |
F- | Monday, July 11, 2011 |
The second attribute that you can apply to @DateTimeFormat is ‘iso’. This gives you a straight forward ISO date time format and applying the different ISO enums will give you the following results:
ISO Value | Result |
---|---|
DateTimeFormat.ISO.DATE_TIME | 2011-07-11T21:28:59.564+01:00 |
DateTimeFormat.ISO.DATE | 2011-07-11 |
DateTimeFormat.ISO.TIME | 21:37:21.394+01:00 |
DateTimeFormat.ISO.NONE | 7/11/11 9:44 PM |
The third and final attribute that can be applied is Pattern. This allows you to format date time values using a specific format string; for example: yyyy/mm/dd h:mm:ss
3 comments:
Hey, very nice site. I came across this on Google, and I am stoked that I did. I will definately be coming back here more often. Wish I could add to the conversation and bring a bit more to the table, but am just taking in as much info as I can at the moment.
iso 9000
Thanks for sharing.
I came across your post when trying to debug my use of the annotation.
Having annotated a field and passed that to the view will that automatically display in JSP or do you need to do something else?
Shaun
Thanks for the comment. The answer to your question is that having annotated a field in your bean, then when the bean is populated and inserted into the Model by your Controller's request handler, then Spring and the Hibernate JSR303 validator will take over and convert your field to the correct value for output by your JSP. You do, of course, have to include the Hibernate JSR 303 validator in your POM as described here: /2011/07/maven-settings-for-hibernate-jsr-303.html
In fact I have a whole series of Blogs on JSR 303, which you may or may not have already found.
Post a comment