Example of SpringMVC converting date types

  • 2020-06-07 04:33:29
  • OfStack

When doing web development, the page is passed in String type, SpringMVC can be converted to some basic types, but for the date class conversion may require configuration.

1. If the query class makes us write our own, we can convert String to Date type by adding @DateTimeFormat (pattern = "yyyy-ES9en-ES10en ") before the attribute, as follows

@DateTimeFormat(pattern = "yyyy-MM-dd") 
private Date createTime; 

2. If we are only responsible for the development of web layer, we need to add data binding in controller:

public void initBinder(WebDataBinder binder) { 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); //true: Null values are allowed, false: Cannot be null 

3, you can add a global type converter to the system

Implementation converter

public class DateConverter implements Converter<String, Date> { 
public Date convert(String source) { 
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
 try { 
  return dateFormat.parse(source); 
 } catch (ParseException e) { 
 return null; 


<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
  <property name="converters"> 
    <bean class="com.doje.XXX.web.DateConverter" /> 

<mvc:annotation-driven conversion-service="conversionService" /> 

4. If the date type is converted to String for display on the page, it needs to be processed with some front-end techniques.

5. When SpringMVC USES @ResponseBody to return json, the date format is displayed as a timestamp by default.

public class CustomObjectMapper extends ObjectMapper { 
 public CustomObjectMapper() { 
  CustomSerializerFactory factory = new CustomSerializerFactory(); 
  factory.addGenericMapping(Date.class, new JsonSerializer<Date>() { 
   public void serialize(Date value, JsonGenerator jsonGenerator, 
     SerializerProvider provider) throws IOException, JsonProcessingException { 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

The configuration is as follows:

  <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
   <property name="objectMapper" ref="customObjectMapper"></property> 

6. When date is converted to json string, long time is returned. If you need to write @JsonFormat (pattern=" yyyy-ES51en-ES52en HH:mm:ss",timezone =" GMT+8") on the get method of the specified date, you can return the object of json as the specified type.

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") 
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 
public Date getCreateTime() { 
return this.createTime; 

Related articles: