import org.springframework.core.convert.converter.Converter; import org.springframework.util.StringUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author lixiao * @date 2019/8/7 14:57 */ public class StringToDateConverter implements Converter<String, Date> { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String SHORT_DATE_FORMAT = "yyyy-MM-dd"; private static final String DATE_FORMAT2 = "yyyy/MM/dd HH:mm:ss"; private static final String SHORT_DATE_FORMAT2 = "yyyy/MM/dd"; private static final String COLON = ":"; private static final String BAR = "-"; private static final String SLASH = "/"; @Override public Date convert(String source) { if (StringUtils.isEmpty(source)) { return null; } source = source.trim(); try { if (source.contains(BAR)) { return getDate(source, DATE_FORMAT, SHORT_DATE_FORMAT); } else if (source.contains(SLASH)) { return getDate(source, DATE_FORMAT2, SHORT_DATE_FORMAT2); } } 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)); } private Date getDate(String source, String dateFormat, String shortDateFormat) throws ParseException { SimpleDateFormat formatter; if (source.contains(COLON)) { formatter = new SimpleDateFormat(dateFormat); } else { formatter = new SimpleDateFormat(shortDateFormat); } return formatter.parse(source); } }
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 javax.annotation.PostConstruct; import javax.annotation.Resource; /** * @author lixiao * @date 2019/7/30 17:26 */ @Configuration public class MvcConfig implements WebMvcConfigurer { @Resource private RequestMappingHandlerAdapter handlerAdapter; /** * 在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法 */ @PostConstruct public void initEditableValidation(){ ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer(); if (initializer != null) { if (initializer.getConversionService() != null) { GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService(); genericConversionService.addConverter(new StringToDateConverter()); } } }
}
在项目中有一种特殊情况是,我们用@RequestBody来接收参数,这时候springboot会使用MappingJackson2HttpMessageConverter来格式化时间,我们还需针对这种情况特殊配置,只需在yml中配置jackson的date-format即可。另外,返回结果时,由于时区问题,可能差8小时,还需配上time-zone。
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8