dateplayframework-2.1ebean

Post timestamp param as a Date for Play!Framework Models?


I'd like Play!Framework to convert a Timestamp sent via POST into a java.util.Date format in the Model, but I don't know if it's directly possible.

Here's my model :

public class Contact extends Model {
    @Id
    private Long id;

    @Constraints.Required
    private String name;

    @JsonIgnore
    @Temporal(TemporalType.TIMESTAMP)
    private Date removed = null; // When the contact is no longer active
}

I tried to add @Formats.DateTime(pattern="?") to removed, but since DateTime use SimpleDateFormat, I wasn't able to found which pattern to use to convert a timestamp to the correct Date.

How can I do ?


Solution

  • Ok I'll answer myself on this, here's what I did (maybe not the best way to do it, but it works).

    I don't use the Model to match the posted param to the removed value, but instead, I do this in my Controller :

    String[] accepts = {"name", "datestamp"};
    Form<Contact> form = Form.form(Contact.class).bindFromRequest(accepts);
    
    Date date = null;
    try {
        date = new Date(Long.parseLong(form.field("datestamp").value()));
    }
    catch (NumberFormatException nfe) {}
    
    if (date == null) {
        form.reject("date", "error.invalid");
    }
    
    if (form.hasErrors()) {
        return badRequest(form.errorsAsJson());
    }
    else {
        Contact contact = form.get();
        contact.setRemoved(date);
    
        contact.save();
        return ok();
    }