Recently I was working on a Spring MVC project. I had an @RequestMapping where one of the method’s @RequestParam arguments was a java.util.Date type. I didn’t think much of it as I was writing the method, until when I tested the application, it threw an exception. I quickly discovered that there’s no String to Date converter registered by default.
So in follow up to my last post where I showed you how to create a JSON collection String to List converter, I’m going to write this quick post to show you how to create a String to Date converter.
public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {
@Override
protected void installFormatters(FormatterRegistry registry) {
super.installFormatters(registry);
registry.addConverter(getStringToDateConverter());
}
public Converter<String, Date> getStringToDateConverter() {
return new Converter<String, Date>() {
@Override
public Date convert(String source) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(source);
} catch (ParseException e) {
return null;
}
}
};
}
}
And that’s all there is to it. Simply replace the SimpleDateFormat pattern with the pattern you need in your application, register the conversion service in your MVC config as mentioned in my previous post and voila!