日期类型转换


springMVC中的几种日期转换格式:



1、在pojo中添加字段
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birthday;

2、在jsp页面中添加input
    <label for="">生日:<input type="text" name="birthday" /></label><br />

3、在controller层查看 参数user的状态


结论:
针对日期类型,springmvc默认没有做类型转换,因此会报告400错误,我们需要配置日期类型转换器

方法1: 在pojo的成员变量上加注解
@DateTimeFormat (pattern= "yyyy-MM-dd" )

方法2:自定义类型转换器
1、定义转换器
package com.qfedu.springmvc.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class DateConverter implements Converter<String, Date>{
    /**
     * 将字符串转换成日期格式
     */
    @Override
    public Date convert(String source) {
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
                sdf.setLenient(false);//是否宽松解析:默认true
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

2、在spring mvc的配置文件中配置转换器
    <!-- 配置注解驱动 -->
    <mvc:annotation-driven conversion-service="myConversion" />
    <!-- 类型转换器 -->
    <bean id="myConversion" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.qfedu.springmvc.converter.DateConverter"></bean>
            </set>
        </property>
    </bean>

方法3:
在controller中添加如下方法
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.classnew CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值