zoukankan      html  css  js  c++  java
  • 日期格式转换

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

         @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>
  • 相关阅读:
    VisionPro 极坐标圆形物体缺陷检测
    VisionPro CogSobeEdgeTool工具
    VisionPro CogLinescanDistortionCorrectionTool工具 图像处理工具
    VisionPro CogIPTwoImageSubtractTool工具 图像处理工具
    云原生技术实践-关键要素和原则
    深度解析项目管理
    商业进化图谱
    一张图理解网络的几个专有名词:数据、段、包、帧、比特
    泛在感知中台建设方案
    区块链生态架构图
  • 原文地址:https://www.cnblogs.com/fbbg/p/13022333.html
Copyright © 2011-2022 走看看