SpringMVC中java时间的处理

本文介绍了一种从前端时间控件传递到后端的日期时间处理方法,详细讲解了如何在Controller层将字符串类型的日期时间转换为Date类型,并提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:请求中的时间应该用什么类型?对应的controller中应该做什么处理?service中的时间类型是不是只能是Date?


解决1:请求中的类型为2018-03-22 15:34:00     service中时间参数为Date类型,controller中怎么处理?

        将请求中的事件类型定义为String,然后再controller中做解决2中的操作,执行查询时传对应的Date参数。解决!


解决2:前端时间控件传到后台的请求时间类型为String,service中时间参数为Date类型,controller中怎么处理?

        Date startDate = null;
        String startDateString = request.getParameter("startDate");
        if (StringUtils.isNotBlank(startDateString)) {
            try {
                startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDateString);
            } catch (ParseException e) {
            }
        }
        Date endDate = null;
        String endDateString = request.getParameter("endDate");
        if (StringUtils.isNotBlank(endDateString)) {
            try {
                endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDateString);
            } catch (ParseException e) {
            }
        }
        log.info("startDate: {} endDate: {}", startDate, endDate);
核心语句:
startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDateString);
将String类型的时间转换成标准"yyyy-MM-dd HH:mm:ss"的Date类型,目标实现。


             

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值