zoukankan      html  css  js  c++  java
  • SpringMVC写一个时间格式转换器(三种方法)

    第一种方法:

    在变量处直接添加@DateTimeFormat(pattern="yyyy-MM-dd")

    第二种方法:

    1.首先新建一个DataConverter实现Converter接口的工具类

    package util;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.regex.Pattern;
    
    import org.springframework.core.convert.converter.Converter;
    
    import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
    
    public class DataConverter implements Converter<String, Date> {
    
    	public Date convert(String source) {
    		//编写时间转换器,支持多种时间格式
    				SimpleDateFormat sdf = getSimpleDateFormat(source);
    				try {
    					Date date = sdf.parse(source);
    					return date;
    				} catch (ParseException e) {
    					e.printStackTrace();
    				} catch (java.text.ParseException e) {
    					// TODO Auto-generated catch block
    					e.printStackTrace();
    				}
    		return null;
    	}
    	private SimpleDateFormat getSimpleDateFormat( String source ) {
    		SimpleDateFormat sdf = new SimpleDateFormat();
    		if( Pattern.matches("^\d{4}-\d{2}-\d{2}$", source )) {
    			sdf = new SimpleDateFormat("yyyy-MM-dd");
    		} else {
    			System.out.println("日期格式错误");
    		}
    		return sdf;
    	}
    }
    

      2.在配合文件中加上

    <!-- 注册转化器 -->
        <mvc:annotation-driven conversion-service="conversion-service"/>    
        <!-- 转换器服务工厂Bean -->
        <bean id="conversion-service"
            class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                <set>
                    <bean class="util.DataConverter" /><!--工具类的class路径-->
                </set>
            </property>
        </bean>
    

      第三种方法:

    1,首先建工具类

    package util;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.annotation.InitBinder;
    
    public class MyDateConverter {
    	@InitBinder
        public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateFormat.setLenient(false);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
        }
    }
    

     2.让controller继承上面这个类

  • 相关阅读:
    Ubuntu20 修改网卡名称
    单臂路由实现不同vlan间通信
    配置trunk和access
    基于端口划分vlan
    Zabbix5.0服务端部署
    搭建LAMP环境部署opensns微博网站
    搭建LAMP环境部署Ecshop电商网站
    Zabbix 监控过程详解
    Zabbix agent端 配置
    Zabbix 监控系统部署
  • 原文地址:https://www.cnblogs.com/zhiyanwenlei/p/10715286.html
Copyright © 2011-2022 走看看