I am trying to write my own formatted one (for DateTime fields, as opposed to java.util.Date fields), but it's hard for me to get this to work. I created my annotation and also extended the AnnotationFormatter class. I call play.data.format.Formatters.register (DateTime.class, the new MyDateTimeAnnotationFormatter ()) when the application loads, but the parsing and printing methods never start.
How am I supposed to do this?
Edit: this code may be useful;)
Annotation class (strongly inspired by the annotation class included in the Play Framework):
@Target({ FIELD }) @Retention(RUNTIME) @play.data.Form.Display(name = "format.datetime", attributes = { "pattern" }) public static @interface JodaDateTime { String pattern(); }
Custom formatting class:
public static class AnnotationDateTimeFormatter extends AnnotationFormatter<JodaDateTime, DateTime> { @Override public DateTime parse(JodaDateTime annotation, String text, Locale locale) throws ParseException { if (text == null || text.trim().isEmpty()) { return null; } return DateTimeFormat.forPattern(annotation.pattern()).withLocale(locale).parseDateTime(text); } @Override public String print(JodaDateTime annotation, DateTime value, Locale locale) { if (value == null) { return null; } return value.toString(annotation.pattern(), locale); }
To register the formatter with the framework, I make this call in the static initializer of the Application class (maybe this would be better if you want to tell where):
play.data.format.Formatters.register(DateTime.class, new AnnotationDateTimeFormatter());
I confirmed with a single click on the debugger that this call was created and that no errors were thrown, but still the formatter did not start, despite annotating the DateTime fields accordingly:
@Formats.JodaDateTime(pattern = "dd.MM.yyyy HH:mm:ss") public DateTime timeOfRequest = new DateTime();
I'm at a loss here.