1

I have a Spring MVC REST backend application. I'm sending the date in "mm/dd/yyyy" format to the client.

But if I format the date in "mm/dd/yyyy" and POST it back, data binding fails.

Here is my Spring customdateserializer obj that converts java.util.date to mm/dd/yyy when sending the date to the frontend

public class CustomDateSerializer extends JsonSerializer<Date> {  
    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws 
        IOException, JsonProcessingException {      

        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        String formattedDate = formatter.format(value);

        gen.writeString(formattedDate);

    }
}

Here is the object for which data binding fails

@Entity
@Table(name = "bill")
public class Bill implements GenericObject {

    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date billDate;

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date getBillDate() {
        return billDate;
    }

    public void setBillDate(Date billDate) {
        this.billDate = billDate;
    }
}

Here is the end point to which I'm posting the data (Spring MVC controller)

@RequestMapping(value = { "/user/{userId}/bill" }, method = { RequestMethod.POST })
    public void addBill(@RequestBody Bill bill_p,@PathVariable("userId") int userId,
            HttpServletResponse httpResponse_p, WebRequest request_p) {

        processing......

    }

1 Answer 1

3

What I can say is that do not send formatted date to the browser. Send the Date type structure\object let the date formatting be handled on the client side. Angular has a date filter for this task.

Similarly for sending data to server, do not send any formatted data but the model date value and i believe the server side deserializer would handle it. See the format being send on the wire for your request.

Sign up to request clarification or add additional context in comments.

2 Comments

Should I send the date from Spring to Angular as is without my customdateserializer?
Thanks. Used the angular filter to display it properly {{ date | date:'MM/dd/yyyy'}}. Now trying to figure out how to use Bootstrap datepicker and package the date properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.