美文网首页
SpringBoot String 转 Date 异常

SpringBoot String 转 Date 异常

作者: 氕氘氚_笔记 | 来源:发表于2018-07-24 11:11 被阅读0次

    通过表单提交发送请求,后台用一个对象接收,类似String,int,Long这样的都能正常接收,一旦有日期类型的(Date)的,无法正常接收,甚至连方法也没有进入,给人一种没有提交到后台的错觉,

    其实并非没有提交到后台,只是在处理的时候,String转换Date转换失败,此时需要手动转换。

    解决

    import org.apache.commons.lang3.StringUtils;
    import org.springframework.core.convert.converter.Converter;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    @Configuartion
    public class StringToDateConverter implements Converter<String,Date> {
        private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
        private static final String shortDateFormat = "yyyy-MM-dd";
        private static final String dateFormat2 = "yyyy/MM/dd HH:mm:ss";
        private static final String shortDateFormat2 = "yyyy/MM/dd";
        @Override
        public Date convert(String source) {
            if (StringUtils.isBlank(source)) {
                return null;
            }
            source = source.trim();
            try {
                SimpleDateFormat formatter;
                if (source.contains("-")) {
                    if (source.contains(":")) {
                        formatter = new SimpleDateFormat(dateFormat);
                    } else {
                        formatter = new SimpleDateFormat(shortDateFormat);
                    }
                    Date dtDate = formatter.parse(source);
                    return dtDate;
                } else if (source.contains("/")) {
                    if (source.contains(":")) {
                        formatter = new SimpleDateFormat(dateFormat2);
                    } else {
                        formatter = new SimpleDateFormat(shortDateFormat2);
                    }
                    Date dtDate = formatter.parse(source);
                    return dtDate;
                }
            } 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));
    
        }
    }
    

    原文 https://www.cnblogs.com/snowstorm/p/8073389.html

    相关文章

      网友评论

          本文标题:SpringBoot String 转 Date 异常

          本文链接:https://www.haomeiwen.com/subject/slsemftx.html