I am developing a Spring/Hibernate web application. I have a DataTranseferObject where the input from the jsp page is stored to be used by different services and eventually saved to a database.
One of the fields in the jsp page is deliveryDate. I want to store it as a date type in the database:
from delivery.java
@Column(name = "DELIVERY_DATE")
private Date deliveryDate;
public void setDeliveryDate(Date deliveryDate){
this.deliveryDate= deliveryDate;
}
public Date getDeliveryDate(){
return deliveryDate;
}
I am trying to validate the field in the jsp page so that only the "yyyy-MM-dd" format is allowed. To do this I have the deliveryDate as a String type in the DataTransferObject and I’m validating it with the @Pattern annotation as such:
@Pattern(regexp="((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])", message="please enter date in fromat yyyy-MM-dd")
@NotNull(message="delivery date is a required field")
private String deliveryDate;
Since I want to store it in the database as a Date type I need to convert the String to a Date type. This I am trying to do using a service:
@Transactional
public Date stringToDateConversion(String stringDate){
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("yyyy-MM-dd");
date = (Date) formatter.parse(stringDate);
return date;
}
but it’s not working since formatter.parse(stringDate) gives "Unhandled exception type ParseException"
I need the service to return a Date type so I can use it in the controller:
Date deliveryDate= deliveryService.stringToDateConversion(deliveryDto.getDeliveryDate());
delivery.setDeliveryDate(deliveryDate);
How do I correctly convert the String to a Date type and return a Date type?
Thanks for the help!
/D
Just handle
ParseExceptionwith call of parsingStringtoDate