配置在Application.Java启动类(Spring boot、Spring cloud):
使用FastJson
/**}
追加StringToDateConverter转换器
package com.ali.sealing.core.utils.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;
/**
* ClassName:StringToDateConverter
* Reason: 入参字符串日期转换器 .
*
* @author yunchao.li
* Date: 2018年4月9日 下午2:42:15
* @version 1.0.0
*/
public class StringToDateConverter implements Converter
/**
* dateFormat:日期时间格式.
*/
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
/**
* shortDateFormat:日期格式.
*/
private static final String shortDateFormat = "yyyy-MM-dd";
/**
* 字符串转换为日期.
* @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
*/
@Override
public Date convert(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
source = source.trim();
try {
if (source.contains("-")) {
SimpleDateFormat formatter;
if (source.contains(":")) {
formatter = new SimpleDateFormat(dateFormat);
} else {
formatter = new SimpleDateFormat(shortDateFormat);
}
Date dtDate = formatter.parse(source);
return dtDate;
} else if (source.matches("^\\d+$")) {
Long lDate = new Long(source);
return new Date(lDate);
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to Date fail", source));
}
throw new RuntimeException(String.format("parser %s to Date fail", source));
}
}
追加Configuration
package com.ali.sealing.core.utils.configuration;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import com.ali.sealing.core.utils.converter.StringToDateConverter;
/**
* ClassName:WebConfigBeans
* Reason: TODO .
*
* @author yunchao.li
* Date: 2018年4月9日 下午2:44:04
* @version 1.0.0
*/
@Configuration
public class WebDateConverterConfiguration {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
/**
* 增加字符串转日期的功能
*/
@PostConstruct
public void initEditableValidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer
.getConversionService();
genericConversionService.addConverter(new StringToDateConverter());
}
}
}