zoukankan      html  css  js  c++  java
  • SpringMvc实现日期转换

    方法一:

      1,自定义日期转换器

      

    public class DataConvert implements Converter<String, Date> {
    
    	  /***
         * 配置时间转换类
         * @param date
         * @return
         */
    	@Override
    	public Date convert(String date) {
    		try {
    			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    			return sdf.parse(date);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    }
    

      2.配置自定义类型转换器

      

       <!--注解驱动-->
       <mvc:annotation-driven conversion-service="format"/>
       
    	<!-- 配置转换器 -->
    	<bean id="format" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    		<property name="converters">
    			<set>
    				<bean class="com.itheima.user.controller.DataConvert"></bean>
    			</set>
    		</property>
    	</bean>
    

      3,在实体Bean上添加@DateTimeFormat,同时记得添加时间格式

      

    @DateTimeFormat(pattern="yyyy-MM-dd")
    	private Date date;
    

      4,不要忘记了添加注解驱动

    <mvc:annotation-driven conversion-service="format"/>
    

      方式二,

      @InitBinder进行时间转换

      创建一个BaseController,在里面创建一个方法,加上@InitBinder注解,对入参为yyyy-MM-dd HH:mm:ss格式的数据进行格式化,将他们转成时间类型。

      

    public class BaseController {
    
    	@InitBinder
    	protected void initBinder(WebDataBinder  binder){
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		sdf.setLenient(false);
    		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, false));
    	}
    }

    @DateTimeFormat(pattern="yyyy-MM-dd")
    	private Date date;

      

  • 相关阅读:
    初识函数定义与调用 * 和 **
    文件操作
    小程序缓存数据
    调用外部的方法
    小程序订单的待付款实现倒计时(秒)
    小程序上线流程
    微信小程序点击保存图片到相册
    修改头像
    点击保存图片
    小程序的学习王战
  • 原文地址:https://www.cnblogs.com/appc/p/8360326.html
Copyright © 2011-2022 走看看