前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >SpringMVC 日期/时间 参数解析

SpringMVC 日期/时间 参数解析

作者头像
前Thoughtworks-杨焱
发布2021-12-07 21:03:48
发布2021-12-07 21:03:48
89200
代码可运行
举报
文章被收录于专栏:杨焱的专栏杨焱的专栏
运行总次数:0
代码可运行

发表于2017-06-042019-01-01 作者 wind

Spring mvc 默认设置对日期和时间参数转换不是很理想,自带的CustomDateEditor 只能传入一个DateFormat,而我们知道SimpleDateFormat 又是线程不安全的,我们可以通过自定义一个PropertyEditorSupport的子类,用其他方式来实现日期格式的转换。少比比,直接上代码:

代码语言:javascript
代码运行次数:0
运行
复制
/*
 * Copyright (c) 2017 西安才多信息技术有限责任公司。
 * 项目名称:dev
 * 文件名称:DateEditor.java
 * 日期:17-6-4 下午2:06
 * 作者:yangyan
 *
 */

package cn.firegod.common.binder;

import cn.firegod.common.utils.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

/**
 * Created by yangyan on 2017/6/4.
 */
public class DateEditor extends PropertyEditorSupport {

    private String pattern[] = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM-dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
            , "yyyy/MM/dd"};


    /**
     * Parse the Date from the given text, using the lang3 DateUtils.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || !StringUtils.hasText(text)) {
            // Treat empty String as null value.
            setValue(null);
        } else {
            try {
                setValue(DateUtils.parseDate(text, pattern));
            } catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }

    /**
     * Format the Date as String, using the lang3 Utils.
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        if (value instanceof java.sql.Date) {
            return (value != null ? DateFormatUtils.ISO_DATE_FORMAT.format(value) : "");
        } else if (value instanceof java.sql.Timestamp) {
            return (value != null ? DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss") : "");
        } else {
            return (value != null ? DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss") : "");
        }
    }
}

然后在我们的 Controller 里面加入下面的代码注册一下,我这里设置在了所有 Controller 的父类上:

代码语言:javascript
代码运行次数:0
运行
复制
@InitBinder
    protected void initBinder(HttpServletRequest request,
                              ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class, new DateEditor());
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档