【SSM - SpringMVC篇】日期格式转换 把英文日期转化为数字日期

日期格式转换

为啥要进行日期格式转换?
springMVC默认不支持页面上的日期字符串到后台的Date的转换
有两种方式
第一种使用注解 第二种编写 转换类,配置到springMVC(了解)

第一种使用注解(简单,建议使用)

在Person类中的Date类型参数上使用注解


public class Person {
    
    
    private int id;
    private String username;
    private String password;
    private String city;
    private Birthday birthday;
    @DateTimeFormat(pattern ="yyyy-MM-dd")
    private Date birthday2;

JSP

 出生日期<input type="date" name="birthday2"/><br/>

日期的格式要看页面传入的数据为准,以此来修改格式
在这里插入图片描述

编写 转换类,配置到springMVC(了解)

编写自定义转换器实现Converter重写方法


//1:将页面上提交的日期字符串,转成Date对象
public class DateTimeFormatConvert implements Converter<String, Date> {
    
    
    public Date convert(String s) {
    
    
        System.out.println("convert "+s);
        //2:转换器
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
    
    
            date = sdf.parse(s);//2020-10-14
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return date;
    }
}

springmvc.xml中配置转换工厂,将我们的转换器设置到converters集合中

 <mvc:annotation-driven conversion-service="formattingConversionService"/>
 
 <bean id="formattingConversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean id="dateTimeFormatConverter" class="com.wzx.util.DateTimeFormatConvert"></bean>
            </set>
        </property>
    </bean>

把英文日期转化为数字日期

add.jsp

把英文日期转化为数字日期


     <!--导入标签-->
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!--调用日期格式化标签-->
<fmt:formatDate value="${item.birthday2}" pattern="yyyy年MM月dd日"/>

猜你喜欢

转载自blog.csdn.net/mighty_Jon/article/details/109092359
今日推荐