• 日期格式转换


    第一种:在实体类中相关字段上加注解

         @DateTimeFormat(pattern="yyyy-MM-dd")//此注解是在往数据库输入数据时转换格式

         @JsonFormat(pattern="yyyy-MM-dd", timezone="GMT+8")

           //此注解是在数据出去时进行转换,该注解不是spring自带,使用时需要配置依赖,但是springboot项目不用再手动配置

    第二种:创建BaseController,然后需要日期类型转换的controller都要继承它

    //使用这个转换器每个controller都要继承才能起作用
    public class BaseController {
    //    日期类型转换器
    //@InitBinder注解的方法可以对WebDataBinder进行初始化,WebDataBinder是DataBinder的子类,用于完成由表单到JavaBean属性的绑定
    //@InitBinder方法不能有返回值,它必须盛名为void
    @InitBinder public void init(WebDataBinder binder){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 严格转换,不会自动对日期进行增减处理 simpleDateFormat.setLenient(false); binder.registerCustomEditor(Date.class,new CustomDateEditor(simpleDateFormat,true)); } }

    第三种:创建日期全局转换器,需要再mvc.xml中进行注册

    //日期全局转换器
    //需要实现Converter<S,T>接口
    public class DateConverter implements Converter<String,Date> {
    
        @Override
        public Date convert(String s) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    //        严格转换:不会自动进行日期的增加处理
            simpleDateFormat.setLenient(false);
            try {
                Date date=simpleDateFormat.parse(s);
                return date;
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return new Date();
        }
    }

    mvc.xml中配置

    <mvc:annotation-driven conversion-service="conversionService">
     </--配置参数输出的转换器-->
    < mvc:message-converters>
       < bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" >
        <property name="objectMapper" >
          <bean class="com.fasterxml.jackson.databind.ObjectMapper" >
            <property name ="dateFormat" >
              <bean class= "java.text. SimpleDateFormat" >
                < constructor-arg type ="javalang.String" value= yyyy-MM-dd"/>|
           </bean>
    </property>
    </bean>
    </property>
    </bean>
    </mvc:message-converters>
    </mvc:annotation-driven>
    //参数输入时的转换器 <bean id="conversionService" class="org.springFramework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.hsxx.controller.DateConverter"/> </set> </property> </bean>
  • 相关阅读:
    职业规划 !!
    linux上ssh配置指南
    低内存VPS用轻量级的Dropbear替换OpenSSH
    修改shell终端提示信息
    减少windows7内存占用的优化方案(内存占用才285兆 比XP还省)
    linux下提示符修改
    mysql存储过程学习笔记区块,条件,循环
    Apache下实现禁止目录浏览
    [学习指导] linux 启动过程以及 /etc/rc.d/init.d/目录的一点理解
    mysql 5.0存储过程学习总结
  • 原文地址:https://www.cnblogs.com/fbbg/p/13022333.html
Copyright © 2020-2023  润新知