springboot日期数据格式问题:实现DateToString &&StringToDate转换方法

xiaoxiao2021-02-28  55

配置在Application.Java启动类(Spring boot、Spring cloud):

使用FastJson

/**   * 编辑fastJson.<br/>   *     * @return HttpMessageConverters * @author yunchao.li */ @Bean     public HttpMessageConverters fastJsonHttpMessageConverters(){         //1、先定义一个convert转换消息的对象         FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();         //2、添加fastjson的配置信息,比如是否要格式化返回的json数据;         FastJsonConfig fastJsonConfig=new FastJsonConfig();         SerializerFeature[] serializerFeatures = new SerializerFeature[]{                 //  输出key是包含双引号 //                SerializerFeature.QuoteFieldNames,                 //  是否输出为null的字段,若为null 则显示该字段 //                SerializerFeature.WriteMapNullValue,                 //  数值字段如果为null,则输出为0 //                SerializerFeature.WriteNullNumberAsZero,                 //   List字段如果为null,输出为[],而非null                 SerializerFeature.WriteNullListAsEmpty,                 //  字符类型字段如果为null,输出为"",而非null                 SerializerFeature.WriteNullStringAsEmpty,                 //  Boolean字段如果为null,输出为false,而非null                 SerializerFeature.WriteNullBooleanAsFalse,                 //  Date的日期转换器                 SerializerFeature.WriteDateUseDateFormat,                 //  循环引用                 SerializerFeature.DisableCircularReferenceDetect,             };         fastJsonConfig.setSerializerFeatures(serializerFeatures);         //附加:处理中文乱码         List<MediaType> fastMedisTypes = new ArrayList<MediaType>();         fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);         fastConverter.setSupportedMediaTypes(fastMedisTypes);         //3、在convert中添加配置信息         fastConverter.setFastJsonConfig(fastJsonConfig);         HttpMessageConverter<?> converter=fastConverter;         return new HttpMessageConverters(converter);

    }

追加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 <br/>    * Reason:   入参字符串日期转换器 . <br/>   * * @author   yunchao.li   * Date:     2018年4月9日 下午2:42:15 <br/>   * @version  1.0.0 <br/>   */public class StringToDateConverter implements Converter<String, Date> {    /**       * 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 <br/>    * Reason:   TODO . <br/>   * * @author   yunchao.li   * Date:     2018年4月9日 下午2:44:04 <br/>   * @version  1.0.0 <br/>   */@Configurationpublic 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());        }    }}  

转载请注明原文地址: https://www.6miu.com/read-2620179.html

最新回复(0)