Title

SpringBoot接收日期参数异常

一、关于接收前端传递的日期参数的问题:

@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")// 空字符串时sql.Date解析报错
@DateTimeFormat(pattern = "yyyy-MM-dd")// 该注解仅对Util.Date类型有效,sql.Date类型解析报错
@JSONField(format = "yyyy-MM-dd")// 空字符串时sql.Date解析报错

1、直接使用sql.Date类型接收时,空字符串解析报错,无法自动映射为null,需要自定义解析

2、使用util.Date类型,并通过@DateTimeFormat(pattern = "yyyy-MM-dd")可以将传递的日期字符串格式化为util.Date类型,但其为格林尼治标准时间2024-01-08T00:00:00.000+0800,不能直接使用

二、方案:

1、Controller层添加以下方法,自定义解析参数(只在该Controller层生效,可以另写一个类,其它类继承它)

@InitBinder
    public void initBinder(WebDataBinder binder){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
            /**
             * Sets the property value by parsing a given String.  May raise
             * java.lang.IllegalArgumentException if either the String is
             * badly formatted or if this kind of property can't be expressed
             * as text.
             *
             * @param text The string to be parsed.
             */
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                try{
                    // 空字符串时直接返回null
                    if(StrUtil.isEmpty(text)){
                        setValue(null);
                        return;
                    }
                    // 先转成java.util.Date,获取毫秒数再转换成sql.Date
                    java.util.Date utilDate = simpleDateFormat.parse(text);
                    setValue(new Date(utilDate.getTime()));
                }catch (Exception ex){
                    throw new GisBootException("sqlDate日期解析错误");
                }

            }
        });
    }

2、使用java.util.date接收参数,在用于查询时格式化为yyyy-MM-dd

posted @   Jackpot_ABC  阅读(575)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示