2021-2-15 前端传入后端日期格式

本文介绍了三种处理日期格式的方法,适用于Spring MVC中前端和后端数据交互。包括配置`spring.mvc.format.date`、使用`@JsonFormat`和`@DateTimeFormat`注解,以及自定义转换器。这些方法确保日期在输入和输出时遵循一致的格式,避免出现日期传入错误。
摘要由CSDN通过智能技术生成

一:spring.mvc.format.date

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/projectCommit?serverTimezone=UTC&useicode=true
    driver-class-name: com.mysql.cj.jdbc.Driver
  mvc:
    format:
      date: dd/MM/yyyy
<input type="date" name="enddate">

解释

将date 类型 格式化

二:value="${review.enddate?string(‘yyyy-MM-dd’)}"

<input type="text" name="enddate" 
value="${review.enddate?string('yyyy-MM-dd')}">

传入后端日期格式错误解决方式
一:

package com.qizhi.config;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class DateConverterConfig implements Converter<String, Date> {


    public Date convert(String source) {
        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(source);
        } catch (ParseException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date;
    }
}

二:此方法需要在每个控制类(servlet,controller)编写


    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
       //格式yyyy-MM-dd HH:mm:ss,不能在更改了,灵活性差
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

三:@DateTimeFormat(pattern=“yyyy-MM-dd”)

	@DateTimeFormat(pattern="yyyy-MM-dd")
    private Date startdate;

    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date enddate;

    private Integer status;

需要传入的字符串类型与这个规则一致

 <tr>
    <td>申报结束日期</td>
    <td><input type="text" name="enddate" value="${review.enddate?string('yyyy-MM-dd')}" readonly></td>
 </tr>

三. @JsonFormat

 	@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat( pattern = "yyyy-MM-dd HH:mm:ss")
    private Date date;
 
    public void setDate(Date date){
        this.date = date;
    }
    public Date getDate(){
        return date;
    }

@DateTimeFormat(pattern=“yyyy-MM-dd HH:mm:ss”) 表示从前台传入后台的字符串规则 将其 转为日期

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss” )表示接口返回的string日期 按照 这个规则 格式化字符串

一般这个两个都是同时使用,保证传入@JsonFormat的字符串格式@DateTimeFormat一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大大陈·

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值